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!
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(':') }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With