Iterate over object(s) if present, single or plural

Viewed 3658

Let's say that i have object my_obj

and i get this object from database, with some more calculation, it doesn't matter...

and then i need to iterate via such object, like:

my_obj.each do |m|
 some_method(m.id)
end

this code is not good, becouse if my_obj is nil, i will get error like:

undefined method `each' for nil:NilClass

so i decide to write:

  if my_obj.present?
    my_obj.each do |m|
     some_method(m.id)
    end
  end

but i think that there is one more way of doing this, without writting everywhere if construction.

so how could i iterate via object, only if it is not null?

9 Answers

in the newer ruby version, tested with 2.4.1, this can be written as

my_obj&.each do |m|
 some_method(m.id)
end
Related