Nested looping

Is there a different way to nest multiple loops?

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

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?

Alex T. 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?
block.call(memo)
else
(head, *tail) = rest
head.each do |x|
_over(memo + [x], tail, block)
end
end
end
_over([], args, block)
end

iterate_over(array1, array2, array3) do |x, y, z|
puts("#{x} #{y} #{z}")
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs