1

This is just a thought exercise and I'd be interested in any opinions. Although if it works I can think of a few ways I'd use it.

Traditionally, if you wanted to perform a function on the results of a nested loop formed from arrays or ranges etc, you would write something like this:

def foo(x, y)
  # Processing with x, y
end

iterable_one.each do |x|
  iterable_two.each do |y|
      my_func(x, y)
  end
end

However, what if I had to add another level of nesting. Yes, I could just add an additonal level of looping. At this point, let's make foo take a variable number of arguments.

def foo(*inputs)
  # Processing with variable inputs
end

iterable_one.each do |x|
  iterable_two.each do |y|
    iterable_three.each do |z|
      my_func(x, y, x)
    end
  end
end

Now, assume I need to add another level of nesting. At this point, it's getting pretty gnarly.

My question, therefore is this: Is it possible to write something like the below?

[iterable_one, iterable_two, iterable_three].nested_each(my_func)

or perhaps

[iterable_one, iterable_two, iterable_three].nested_each { |args| my_func(args) }

Perhaps passing the arguments as actual arguments isn't feasible, could you maybe pass an array to my_func, containing parameters from combinations of the enumerables?

I'd be curious to know if this is possible, it's probably not that likely a scenario but after it occurred to me I wanted to know.

2 Answers 2

4

Array.product yields combinations of enums as if they were in nested loops. It takes multiple arguments. Demo:

a = [1,2,3]
b = %w(a b c)
c = [true, false]

all_enums = [a,b,c]
all_enums.shift.product(*all_enums) do |combi|
  p combi
end


#[1, "a", true]
#[1, "a", false]
#[1, "b", true]
#...
Sign up to request clarification or add additional context in comments.

2 Comments

Facepalm. Totally forgot about product.
I even used it for something the other day. Oh well, at least that's my curiosity satisfied. Early night clearly needed...
3

You can use product:

[1,4].product([5,6],[3,5])  #=> [[1, 5, 3], [1, 5, 5], [1, 6, 3], [1, 6, 5], [4, 5, 3], [4, 5, 5], [4, 6, 3], [4, 6, 5]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.