Greetings!
Let me start by clarifying that this is just a request for style
suggestions... So I won't be hugely disappointed if the plain old way
works just fine.
I have two arrays. let's call them foo and bar.
foo = [ "a", "b", "c", ... n ]
bar = [ 1 , 2 , 3 , ... m ]
I am looking for a way to combine them such that the result is something like
[ [ "a", 1 ], [ "a", 2 ], ... [ "a", m ], [ "b", 1 ], ... [ n, 1 ],
... [ n, m ] ]
I thought that foo * bar would do it, but upon it failing I checked
with the Pickaxe and found that it was not the case. Now, I could just
do
baz = []
foo.each do |f|
bar.each do |b|
baz << [ f, b ]
end
end
and that would be just fine, but I was wondering if there was any
magical Ruby library/module that already does this. Maybe an extension
for Array that allows Array * Array, or something
that provides Array.combine( Array ). I performed a web search for
array combination/permutation(1) in Ruby and didn't get any relevant
results, which is why I'm asking here.
Again, this is just a matter of style. An answer along the lines of
"the nested loops are as good as it'll get for you" is completely
acceptable.
Many regards...
-CWS
(1): The order of elements is important. I'm looking for combinations,
not permutations. But I searched for the latter anyway since
"combination" is too much of a common word and combinations and
permutations usually go hand in hand.