数组 – 使用%w或%W的变量 – Ruby

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

解决方法

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

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

正确的做法是:

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

像%W [#{}}这样的事情和“#{…}”一样毫无意义.如果你需要一些强制转换为字符串,请调用.to_s.如果你需要拆分呼叫拆分.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...