Forum: Ruby on Rails nested looping

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
03d789b32a9e9c47a678f0ac173f5c13?d=identicon&s=25 Alex Treber (Guest)
on 2007-01-26 15:49
Is there a different way to nest multiple loops?

arr = []
var1.each do |a|
  var2.each do |b|
     var3.each do |c|
        arr << b if !arr.include?(b)

Just wondering if there was a way to clean up these 8 lines in order to
run the 2 lines inside.

its possible to write a single loop
var1.each {|a| single_line_of_code(a)}

but would this work and follow conventions to just dump the rest inside?
F5c118aaeb5bb7162db613a37e595be8?d=identicon&s=25 Mick Sharpe (micksharpe)
on 2007-01-27 13:57
Alex Treber wrote:
> Is there a different way to nest multiple loops?

Not built into the Ruby language as far as I know, but there's nothing
stopping you from rolling your own code if you need to do a lot of this:

array1 = [ 1, 2, 3 ]
array2 = [ 4, 5, 6 ]
array3 = [ 7, 8, 9 ]

def iterate_over(*args, &block)
  def _over(memo, rest, block)
    if rest.empty?
      (head, *tail) = rest
      head.each do |x|
        _over(memo + [x], tail, block)
  _over([], args, block)

iterate_over(array1, array2, array3) do |x, y, z|
  puts("#{x} #{y} #{z}")
This topic is locked and can not be replied to.