Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add nil object as an element of an array in Ruby

Tags:

ruby

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?

like image 470
user384070 Avatar asked Nov 26 '25 16:11

user384070


2 Answers

Use:

a = [nil]

Example:

> 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
=> [nil]
like image 66
Mark Byers Avatar answered Nov 29 '25 14:11

Mark Byers


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"

like image 43
adamse Avatar answered Nov 29 '25 15:11

adamse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!