使用%w或%W的变量 - Ruby

时间:2017-01-29 18:16:44

标签: arrays ruby string variables

我和这篇文章有类似的问题:     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

1 个答案:

答案 0 :(得分:6)

%w不打算进行任何拆分,这是表达源中的以下字符串应该被拆分的一种方式。从本质上讲,它只是一个简写符号。

%W的情况下,#{...}块被视为单个标记,其中包含的任何空格都被视为不可分割的部分。

正确的做法是:

words = text.trim.split(/\s+/)

%W[#{...}]这样的事情与"#{...}"一样毫无意义。如果您需要演员作为字符串,请致电.to_s。如果您需要拆分呼叫split