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!
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.
My suggestion would be to split the problem into two separate problems. In this case, the following:
While messy, I would perhaps do something along this path:
def foo
#declare our known values as arrays, and initialize the container of the final result.
combined_array = []
array_letters = ['x', 'y', 'z']
array_numbers = ['1', '2']
array_letters.each do |letter|
array_numbers.each do |number|
combined_array << "#{letter}:#{number}"
end
end
#return our new array
combined_array
end
Now mind you, I am sure there is a better way to do this. But in consideration, I am fairly certain this should work.