开发者

putting enumeration with spaces in rails collection

irb(main):001:0> t = %w{this is a test}
=> ["this", "is", "a", "test"]
irb(main):002:0> t.size
=> 4
irb(main):003:0&开发者_如何学JAVAgt; t = %w{"this is" a test}
=> ["\"this", "is\"", "a", "test"]
irb(main):004:0> t.size
=> 4

In the end I expected t.size to be 3.

As suggested, each space has to be escaped ...which turns out to be a lot of work. What other options are there? I have a list of about 30 words that I need to put in a collection because I am showing them as checkboxes using simple_form


Why not just use a normal array so no one has to visually parse all the escaping to figure out what's going on? This is pretty clear:

t = [
    'this is',
    'a',
    'test'
]

and the people maintaining your code won't hate you for using %w{} when it isn't appropriate or when they mess things up because they didn't see your escaped whitespace.


You need to escape the space with a '\', like t = %w{this\ is a test} if you dont want that space to be a splitter.


Escape the space using \:

%w{this\ is a test}


You can escape the space %w{this\ is a test} to get ['this is', 'a', 'test'], but in general I wouldn't use %w unless then intention is to split on whitespace.


As others have pointed out use the %w{} construct when spaces are the separator for the words. If you have items that must be quoted and still want to use the construct you can do:

 > %w{a test here}.unshift("This is")  
 => ["This is", "a", "test", "here"] 


require 'csv'
str = '"this is" a test'
p CSV.parse_line(str,{:col_sep=>' '})
#=> ["this is", "a", "test"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜