1

I have two arrays and I can join them looping these two arrays. But is there better way of doing it?

colors = ['yellow', 'green']
shirts = ['s','m','xl','xxl']

Output required:

output = ['yellow_s','yellow_m','yellow_xl','yellow_xxl','green_s','green_m','green_x','green_xxl']

2 Answers 2

7

Using Array#product, you can get cartesian product:

colors = ['yellow', 'green']
shirts = ['s','m','xl','xxl']
colors.product(shirts).map { |c, s| "#{c}_#{s}" }
# => ["yellow_s", "yellow_m", "yellow_xl", "yellow_xxl",
#     "green_s", "green_m", "green_xl", "green_xxl"]

colors.product(shirts).map { |e| e.join("_") }
# => ["yellow_s", "yellow_m", "yellow_xl", "yellow_xxl",
#     "green_s", "green_m", "green_xl", "green_xxl"]
Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively colors.product(shirts).map{|e| e.join("_")}
@Candide, Thank you for suggesting the alternative. I added it to the answer.
Thank you Guys. I was not aware of this method.
0

I used this method.

colors = ['green', 'yellow']
shirts = ['s','m', 'xl', 'l']
selection = []
x = 0
while x < shirts.length
  selections.push(colors.map{|c|c + "_" + shirts[x]})
  x += 1
end
selections.flatten!

=> ['yellow_s', 'green_s', 'yellow_m', 'green_m', 'yellow_xl', 'green_xl', 'yellow_xxl', 'green_xxl']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.