nanakondor
nanakondor

Reputation: 745

Ruby add nil value to an array

How can I initialize an array and be able to add nil value to it? as I know Array.wrap doesn't do the job.

list = Array.wrap(nil) => []

What I want:

list = Array.add(nil) => [nil]

Thank you

Upvotes: 0

Views: 1673

Answers (2)

iGian
iGian

Reputation: 11183

Maybe you are looking for (Rails):

list = Array.wrap([nil])
#=> [nil]

But why not just a simple list = [nil], as per @engineersmnky's comment?

Also list = Array.new.push nil, but it's still better the easy way above.

Upvotes: 0

Mark
Mark

Reputation: 6445

Try:

list = Array.new(1)

The number fed in as an argument dictates how many nils are added:

list = Array.new(3)
=> [nil, nil, nil]

Upvotes: 1

Related Questions