Is there a way to use .each
so it does not throw an error if the object is nil or empty (without adding an additional nil/blank test?
It seems that if I say phonelist.each do |phone|
that if phonelist is empty, then the block should not be executed.
But in my view (haml) I have - @myvar.phonelist.each do |phone|
and if phonelist is empty, it throws a NoMethodError.
I run into this a lot, and always workaround by adding an explicit check/branch for .blank? but it seems there should be an easier way to tell .each that empty means do nothing.
In Ruby, nil is—you've guessed it—an object. It's the single instance of the NilClass class. Since nil in Ruby is just an object like virtually anything else, this means that handling it is not a special case.
nil is a special Ruby data type that means "nothing". It's equivalent to null or None in other programming languages.
But in Ruby, nil is an object. You can use it as a value, you can call methods on it, you can define methods for it. It's not NULL and it doesn't make your programs vulnerable to things that NULL makes your program vulnerable to.
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
You can use the try method to call .each on a nil so it does not throw an error if the object is nil or empty.
phonelist = nil phonelist.try(:each){|i| puts i}
Simply do the following:
Array(phonelist).each do |phone| #deal with your phone end
Array(my_variable) will ensure to return an array if my_variable is nil.
It doesn't create a new Array if my_variable is already an array, so it is safe and light to use it wherever you want !
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