0

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

2
  • 6
    How about using literal syntax [nil] Commented Feb 19, 2020 at 14:40
  • Based on the comments it appears that the question is, “How can I create an array that contains a single, given object?”. Correct? If so, do as @engineersmnky suggests, replacing nil with the given object if it is something other than nil. If the object is held by a variable x, write [x]. Commented Feb 19, 2020 at 17:04

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

6 Comments

I'm adding a variable to the array and I don't know if its nil or not. like Array.wrap(item)
@nanakondor just write [item]
The question was literally How can I initialize an array and be able to add nil value to it?
@nanakondor What @Stefan said but if item can also be an Array I would change this to [*item] to better simulate the way Array#wrap works (which by the way is a rails method so I added the rails tag.
@engineersmnky although having to deal with objects that can either be nil or arrays or non-arrays might indicate some underlying problems.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.