Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1: Ruby idiom to prevent .each from throwing exception if nil?

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.

like image 568
jpw Avatar asked Mar 06 '12 23:03

jpw


People also ask

How do you handle nil in Ruby?

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.

What does != Nil in Ruby mean?

nil is a special Ruby data type that means "nothing". It's equivalent to null or None in other programming languages.

Is nil null in Ruby?

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.

How do you know if a Ruby is nil?

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).


2 Answers

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} 
like image 119
johnnyx25 Avatar answered Sep 24 '22 13:09

johnnyx25


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 !

like image 22
Arkan Avatar answered Sep 21 '22 13:09

Arkan