Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Pair individual values of two arrays into third array

Tags:

arrays

ruby

I have two arrays: ['x','y','z'] and [1,2]. How would I go about creating pairs of values (as a string) in a third array?

So I would end up with this:

['x:1', 'x:2', 'y:1', 'y:2', 'z:1', 'z:2']

Thanks for any help!

like image 417
Kevin Whitaker Avatar asked Dec 07 '22 00:12

Kevin Whitaker


2 Answers

You can use the product method to create the pairs and then join them:

a1 = ['x','y','z']
a2 = [1,2]
a1.product(a2).map {|p| p.join(':') }
like image 151
Phil Ross Avatar answered Mar 07 '23 14:03

Phil Ross


Here's a way that's short and efficient, and reads well.

a1 = ['x','y','z']
a2 = [1,2]

a1.flat_map { |e| a2.map { |f| "#{e}:#{f}" } }
  #=> ['x:1', 'x:2', 'y:1', 'y:2', 'z:1', 'z:2']

I originally had a2.map { |f| e.to_s+?:+f.to_s }. I replaced flat_map with map and e.to_s+?:+f.to_s with "#{e}:#{f}", as suggested by @PhilRoss and @Stefan, respectively. Thanks to both of you.

like image 33
Cary Swoveland Avatar answered Mar 07 '23 14:03

Cary Swoveland