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
No. The whole purpose of that convenience syntax is to avoid putting quotes around string literals, and the separator comma.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With