3

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']]
0

3 Answers 3

6

You can use Array#product:

x = ['A', 'B', 'C']
y = ['D', 'E', 'F']

result = x.product(y)

puts result.inspect
Sign up to request clarification or add additional context in comments.

3 Comments

I was waiting for somebody to come along and blow my answer out of the water. A begrudging +1. :)
Wow. That's exactly what I was looking for. I was looking through the Ruby Core API and somehow missed this one.
@JasonSwett I definitely learned from your solution. A +1 to you as well. ^_^
2

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

5 Comments

This might be the best way. I could replace your y.each with result << y.map{|item| [item, x] } I believe.
Thanks for looking into that. I'll accept your answer when it lets me. I appreciate your assistance.
No problem. Another thought, and maybe you already know about this, but I might personally use collect, an alias for map, instead of map here. Even though the two functions do the same exact thing, I find the collect name to be more intent-revealing in these kinds of cases.
Okay, I was going to accept this, but the other answer does exactly what I wanted in the most concise way possible. Using #product seems to be the trick. Thanks again.
Or, even better, use the other guy's better answer.
0

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"]]

1 Comment

Isn't that the same as x.zip(y)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.