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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With