Iterate over an object (s), if any, one or more

Say I have my_obj object

and I get this object from the database, with some calculations, it doesn't matter ...

and then I need to iterate through an object like this:

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

this code is not good, because if my_obj is zero, I will get an error, for example:

undefined method `each' for nil:NilClass

so I decided to write:

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

but I think there is another way to do this without attributing the construction everywhere.

so how can i iterate through an object only if it is not null?

+4
source share
8 answers

- ", ". .

, ActiveRecord:: Relation object, each [].

Article.count
# => 0

articles = Article.all # Return array in Rails 3
articles.each { |a| puts a.title }
# => []

articles = Article.scoped # Return ActiveRecord::Relation object in Rails 3
articles.each { |a| puts a.title }
# => []

. , , . .

+5

- "Array", nil , , .

>> Array(nil)
=> []

>> Array([1])
=> [1]

, :

Array(my_obj).each do |m|
 some_method(m.id)
end
+4

, . nil NullObjects, . :

my_object.to_a.each do |m|
  some_method(m.id)
end

my_object.try(:each) do |m|
  some_method(m.id)
end

(my_object || []).each do |m|
  some_method(m.id)
end
+3

Rails Object#try :

my_object.try(:each) do |m|
  some_method(m.id)
end

each ( ) , my_object nil. each nil.

+2

:

def fields_each(fields)
  if fields.present? && fields.keys.present?
    fields.each do |key, value|
      yield(key, value) if block_given?
    end
  end
end

and use;

fields_each({a: 1, b: 2, c: 3}) do |key, value|
  puts "Key: #{key} value: #{value}"
end
+2
source

Everyone forgot amazing [my_objects].flatten.compact!

+1
source

when you initialize my_objfollow these steps

my_obj = Model.all || [] # Empty array will not iterate or throw error

Example:

[].each do |x|
  p "I will not execute"
end
0
source

you can try this above loop:

   if my_obj == nil then
    redirect_to "something_else"
   end
0
source

All Articles