我有一个与这篇文章类似的问题: How to use variable inside %w{} 但我的问题有点不同。我想获取一个字符串变量并使用 %w 或 %W 将其转换为数组。
text = gets.chomp # get user text string
#e.g 我输入“先进先出”
words = %w[#{text}] # convert text into array of strings
puts words.length
puts words
控制台输出
1
first in first out
将文本保留为字符串 block ,不将其拆分为数组单词 ["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
最佳答案
%w
不打算进行任何拆分,它是一种表达源代码中的以下字符串 应该拆分的方式。本质上它只是一种速记符号。
在 %W
的情况下,#{...}
block 被视为单个标记,其中包含的任何空格都被视为不可分割的一部分。
正确的做法是:
words = text.trim.split(/\s+/)
像 %W[#{...}]
这样的事情和 "#{...}"
一样毫无意义。如果您需要将某些内容转换为字符串,请调用 .to_s
。如果您需要拆分调用 split
。
关于arrays - 使用带有 %w 或 %W 的变量 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924301/