Add nil object as an element of an array in Ruby

0 votes
asked Aug 12, 2010 by user384070

Can I have an array which has nil as a value in it?, e.g., [1, 3, nil, 23].

I have an array in which I assign nil like this array = nil, and then I want to iterate through it but I can't. The .each method fails saying nil class.

Is it possible to do this?

5 Answers

0 votes
answered Aug 12, 2010 by mark-byers


a = [nil]


> a = nil
=> nil
> a.each{|x|puts x}
NoMethodError: undefined method `each' for nil:NilClass
        from (irb):3
        from :0

> a= [nil]
=> [nil]
> a.each{|x|puts x}
=> [nil]
0 votes
answered Aug 12, 2010 by adamse

I believe your problem lies in when you "assign nil" to the array

arr = []
arr = nil

Is this something like what you tried doing? In this case you do not assign nil to the array you assign nil to the variable arr, hence arr is now nil giving you errors concerning a "nil class"

0 votes
answered Aug 12, 2010 by jed-schneider

use Enumerable#map

ruby-1.8.7-p249 > [1,2,nil,4].map{|item| puts item}
 => [nil, nil, nil, nil] 

note that even though the return is nil for each item in the array, the original array is as it was. if you do something to operate on each item in the array, it will return the value of each operation. you can get rid of nils buy compacting it.

ruby-1.8.7-p249 > [1,2,nil,4].map{|item| item + 1 unless item.nil? }
 => [2, 3, nil, 5] 
ruby-1.8.7-p249 > [1,2,nil,4].map{|item| item + 1 unless item.nil? }.compact
 => [2, 3, 5] 
0 votes
answered Aug 12, 2010 by john-dibling

Sure you can. You are probably trying to do something with the nil object without checking to see if it's nil? first.

irb(main):001:0> a = [1,2,nil,3]
=> [1, 2, nil, 3]
irb(main):003:0> a.each{|i|
irb(main):004:1* if i.nil? then
irb(main):005:2* puts ">NADA>"
irb(main):006:2> else
irb(main):007:2* puts i
irb(main):008:2> end
irb(main):009:1> }
=> [1, 2, nil, 3]
0 votes
answered Aug 12, 2010 by telemachus

I think you're confusing adding an item to an array with assigning a value of nil to a variable.

Add an item to (the end of) an array (two ways):

# or if you prefer
array << item
# works great with nil, too
array << nil

I'm assuming that the array already exists. If it doesn't, you can create it with array = [] or array =

On the other hand, array = nil assigns nil to a variable that happens to be (misleadingly) named 'array'. If that variable previously pointed to an array, that connection is now broken.

You may be thinking of assignment with an index position, but array[4] = nil is very different from array = nil.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter