2 Arrays into 1 Array with all possible combinations?

I have 2 arrays like so:

arr1 = [a, b, c]
arr2 = 1, 2, 3]

I want to get:

[a1, a2, a3, b1, b2, b3, c1, c2, c3]

I’ve tried a few things like

output = arr1.each do |a1|
arr2.each do |a2|
end
end

puts output

But that only lists the first array.

This works:
output = arr1.each do |a1|
arr2.each do |a2|
puts a1 + a2
end
end

But my “output” variable isn’t good. I get the desired text in the
console, but I can’t reuse it for what I really want to do.

This seems trivial, but I feel stupid. I can’t even search for this
properly. Please help… thanks.

On Dec 19, 2013, at 3:37 AM, Mike L. [email protected] wrote:

I have 2 arrays like so:

arr1 = [a, b, c]
arr2 = 1, 2, 3]

I want to get:

[a1, a2, a3, b1, b2, b3, c1, c2, c3]

Heres one way:

a1 = %w{a b c}
=> [“a”, “b”, “c”]

a2 = %w{1 2 3}
=> [“1”, “2”, “3”]

a1.map {|c1| a2.map {|c2| c1 + c2} }.flatten
=> [“a1”, “a2”, “a3”, “b1”, “b2”, “b3”, “c1”, “c2”, "c3]

HTH,
Ammar

a1 = [“a”, “b”, “c”]
a2 = [“1”, “2”, “3”]

a1.product(a2)

=> [[“a”, “1”], [“a”, “2”], [“a”, “3”], [“b”, “1”], [“b”, “2”],

[“b”, “3”], [“c”, “1”], [“c”, “2”], [“c”, “3”]]

a1.product(a2).map {|a| a.join }

=> [“a1”, “a2”, “a3”, “b1”, “b2”, “b3”, “c1”, “c2”, “c3”]

a1.product(a2).map(&:join)

=> [“a1”, “a2”, “a3”, “b1”, “b2”, “b3”, “c1”, “c2”, “c3”]

same as above

If you want to different things with one element

a1.product(a2).map {|el1, el2| el1.upcase + el2 }
=> [“A1”, “A2”, “A3”, “B1”, “B2”, “B3”, “C1”, “C2”, “C3”]

Best regards,
Abinoam Jr.

Am 19.12.2013 02:57, schrieb Ammar A.:

a1 = %w{a b c}
=> [“a”, “b”, “c”]

a2 = %w{1 2 3}
=> [“1”, “2”, “3”]

a1.map {|c1| a2.map {|c2| c1 + c2} }.flatten
=> [“a1”, “a2”, “a3”, “b1”, “b2”, “b3”, “c1”, “c2”, "c3]

That’s it! Thank you!

On Dec 19, 2013, at 7:31 AM, [email protected] wrote:

@Ammar: “>>” is rendered as quote by many email clients,
so using it as prompt is not so good in a mailing list.

I did not notice that. Thanks for pointing it out.

Regards,
Ammar

On Dec 19, 2013, at 4:11 AM, Mike L. [email protected] wrote:

That’s it! Thank you!

I actually like Abinoams suggestion better.

a1.product(a2).map(&:join)

Regards,
Ammar

Thanks.

Yukihiro M.: Ruby inherited the Perl philosophy of having MORE
THAN ONE WAY to do the same thing.
(http://www.artima.com/intv/rubyP.html)

That’s why it’s a cool language !!! :wink:

ar1=[‘a’,‘b’,‘c’]
ar2=[1,2,3]
ar3=Array.new()

ar1.each do |a| ar2.each do |n| ar3.push(a+n.to_s) end end
p ar3

ar3 = [ar1, ar2]
ar3.flatten.permutation.map(&:join)

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