加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:07:38 所属栏目:百科 来源:网络整理
导读:我和这篇文章有类似的问题: ???? How to use variable inside %w{} 但我的问题有点不同.我想获取一个字符串变量并使用%w或%W将其转换为数组. text = gets.chomp # get user text string #例如我输入“先进先出” words = %w[#{text}] # convert text into
我和这篇文章有类似的问题:
???? 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.如果你需要拆分呼叫拆分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读