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?
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]
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With