Create array with empty string using %w[]

二次信任 提交于 2020-02-03 03:59:46

问题


To create an array with empty strings ['a', '', 'b', '', 'c'] (not one space strings ' '), using %W I can use %W[a #{} b #{} c], also I can concatenate arrays, but is it possible to create array with empty strings using just %w[]?


回答1:


A couple of options

%W[a b c #{''} z]

%W[a b c] << " "

(I know this isn't using the %w{} syntax, but for good measure:

'a,b,c,,z'.split(',')




回答2:


You can use

 %w[a \   b \  c].map(&:strip)

,but I think it's not very clean.




回答3:


try using %W instead of %w and use \s escape character for the empty string

 %W[a \s b ]



回答4:


You can use escape operator (\) with an extra space character after it.

>> %w(a \  b \  c)
=> ["a", " ", "b", " ", "c"]


来源:https://stackoverflow.com/questions/12979928/create-array-with-empty-string-using-w

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!