@ users.each do | user | --- Is there a way to do this for multiple objects

Now I am doing:

@users.each do |user| 

Given that I have @users, @ users1, @ users2

Is there any way to do:

 [@users, @users1, @users2].each do |user| 

If every cycle goes through all the objects?

thanks

+4
source share
3 answers

You can combine arrays and iterate over the result:

 (@users + @users1 + @users2).each do |user| ... end 

It may be tempting to use a flattened one, but you should be careful with it. A simple call to no-arguments flatten does not behave as you would expect if any elements of any array are themselves arrays:

 users, users1, users2 = [1,2], [ [3,4], [5,6] ], [ 7,8] puts [users,users1,users2].flatten.inspect # Will print [1, 2, 3, 4, 5, 6, 7, 8] # Two small arrays are smashed!!! 

However, as jleedev suggests in one of the comments, a flatten function in Ruby can take an integer argument, which determines the maximum level the arrays will be broken, so:

 puts [users,users1,users2].flatten(1).inspect # Will print [1, 2, [3, 4], [5, 6], 7, 8] # Just as planned. 
+10
source
 [@users,@users1,@users2].flatten.each do |user| 
+3
source

Various methods:

 # Concatenate (@ users+@users1 +@users2 ).each{ ... } # Splat (Ruby 1.9 only) [*@users,*@users1,*@users2].each{ ... } # Interleave them @users.zip( @users1, @users2 ).each{ |u,u1,u2| ... } 
+3
source

All Articles