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

Say I want to create an array with ["one", "two", nil], can this be done using shorthand syntax %w[]? Obviously this does not work:

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

Ruby 1.9.3

+5
source share
3 answers

No. The whole purpose of this convenient syntax is to not put quotation marks around string literals and a separator comma.

+4
source

You can split the array %w[]and put nilafter:

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

But it can be noisier than just specifying the lines individually; OTOH, the extra noise indicates that something strange is happening, so readers will be asked to get close to them.

+1
source

. , "nil" # collect:

array = %w[one two nil].collect { |v| v == 'nil' ? nil : v }
0

All Articles