arrays - 使用带有 %w 或 %W 的变量 - Ruby

标签 arrays ruby string variables

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

相关文章:

python - 在 PyTorch 中将张量向量化分配给切片

c++ - vector 数组 C++ - 添加元素时的奇怪行为

Ruby、DB2/400、ibm_db 导致 "segmentation fault"

python - 正则表达式 Python 在单个表达式中提取两个字符串之间的数字

java - 将字符串转换为 ASCII 以及将 ASCII 转换为字符串

c++ - 为什么 C++ 为我的动态数组分配如此大的内存空间?

arrays - 如何在标签中显示数组?

ruby - Bosh stemcell Ubuntu Ruby,与/var/vcap/bosh/lib/ruby 冲突(LoadError)

ruby - 定义 Ruby 类方法的方式有区别吗?

java - Java中字符串索引越界