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

Nak*_*kii 4 ruby arrays string variables

我有一个与这篇文章类似的问题: 如何在%w {}内部使用变量, 但我的问题有点不同.我想获取一个字符串变量并使用%w或%W将其转换为数组.

text = gets.chomp   # get user text string
Run Code Online (Sandbox Code Playgroud)

#eg我输入"先出先出"

words = %w[#{text}]  # convert text into array of strings

puts words.length
puts words
Run Code Online (Sandbox Code Playgroud)

控制台输出

1
first in first out
Run Code Online (Sandbox Code Playgroud)

将文本保留为字符串块,不将其拆分为数组字["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
Run Code Online (Sandbox Code Playgroud)

tad*_*man 6

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

在将块视为单个令牌的情况下,%W其中#{...}包含的任何空间都被视为不可分割的部分.

正确的做法是:

words = text.trim.split(/\s+/)
Run Code Online (Sandbox Code Playgroud)

做同样的事情就像%W[#{...}]没有意义一样"#{...}".如果您需要演员作为字符串,请致电.to_s.如果你需要拆分电话split.