我有一个类似的问题,这篇文章:How to use variable inside %w{},但我的问题有点不同。我希望接受一个字符串变量,并使用%W或%w将其转换为数组。
text = gets.chomp # get user text string#例如,我输入“先到先出”
words = %w[#{text}] # convert text into array of strings
puts words.length
puts words控制台输出
1
first in first out将文本保持为字符串块,不将其拆分为数组单词"first“、"in”、"first“、"out”
words = text.split (" ") # This works fine
words = %w[#{gets.chomp}] # This doesn't work either
words = %w['#{gets.chomp}'] # This doesn't work either
words = %W["#{gets.chomp}"] # This doesn't work either
words = %w("#{gets.chomp}") # This doesn't work either发布于 2017-01-29 18:21:10
%w并不打算进行任何拆分,它是表示源中的以下字符串应该被拆分的一种方式。从本质上说,这只是一个简短的符号。
在%W的情况下,#{...}块被视为单个令牌,其中包含的任何空格都被认为是一个完整的部分。
正确的做法是:
words = text.trim.split(/\s+/)做像%W[#{...}]这样的事情和"#{...}"一样毫无意义。如果需要将某些内容转换为字符串,请调用.to_s。如果你需要什么拆分电话,打电话给split。
https://stackoverflow.com/questions/41924301
复制相似问题