Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm currently doing:

@users.each do |user|

Given I have @users, @users1, @users2

Is there a way to do:

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

Having the each loop go through all the objects?

Thanks

like image 358
AnApprentice Avatar asked Dec 04 '22 22:12

AnApprentice


1 Answers

You can concatenate the arrays and iterate the result:

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

It may be tempting to use flatten, but you should be careful with it. A simple no-arguments flatten call doesn't behave the way you expect if any elements of any array are arrays themselves:

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, flatten function in Ruby may accept an integer argument that defines the maximum level the arrays will be smashed to, so:

puts [users,users1,users2].flatten(1).inspect
# Will print [1, 2, [3, 4], [5, 6], 7, 8]
# Just as planned.
like image 92
P Shved Avatar answered Feb 15 '23 00:02

P Shved