Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a nil value in an array using %w[] shorthand?

Tags:

arrays

ruby

Say I want to create an array with ["one", "two", nil], is it possible to do so using shorthand %w[] syntax? Obviously this does not work:

array = %w[one two nil]
=> ["one", "two", "nil"]
array[2].nil?
=> false

Ruby 1.9.3

like image 790
Mohamad Avatar asked Jun 05 '12 20:06

Mohamad


2 Answers

No. The whole purpose of that convenience syntax is to avoid putting quotes around string literals, and the separator comma.

like image 148
Anil Avatar answered Nov 09 '22 02:11

Anil


You could splat the %w[] array and put the nil after:

>> array = [ *%w[one two], nil, *%w[and some more words] ]
=> ["one", "two", nil, "and", "some", "more", "words"]

But that might be noisier than just quoting the strings individually; OTOH, the extra noise does indicate that something odd is going on so readers would be encouraged to look closer.

like image 42
mu is too short Avatar answered Nov 09 '22 02:11

mu is too short