Reputation: 9895
What is the best way to merge the following two arrays into a multidimensional array?
x = ['A', 'B', 'C']
y = ['D', 'E', 'F']
Desired result:
z = [['A', 'D'], ['A', 'E'], ['A', 'F'], ['B', 'D'], ['B', 'E'], ['B', 'F'], ['C', 'D'], ['C', 'E'], ['C', 'F']]
Upvotes: 3
Views: 1204
Reputation: 7338
Another way of doing it is like this:
x = ['A', 'B', 'C']
y = ['D', 'E', 'F']
print x.concat(y).each_slice(2).to_a # => [["A", "B"], ["C", "D"], ["E", "F"]]
Upvotes: 0
Reputation: 2847
You can use Array#product:
x = ['A', 'B', 'C']
y = ['D', 'E', 'F']
result = x.product(y)
puts result.inspect
Upvotes: 6
Reputation: 45074
Here's one way, although not necessarily the simplest possible way:
x = ['A', 'B', 'C']
y = ['D', 'E', 'F']
result = []
x.each do |x|
y.each do |y|
result << [x, y]
end
end
puts result.inspect
Update: here's a more concise way:
x = ['A', 'B', 'C']
y = ['D', 'E', 'F']
puts x.map { |x|
y.map { |y| [x, y] }
}.inspect
Upvotes: 2