4

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!

3 Answers 3

11

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(':') }
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

a2.flat_map could be replaced with a2.map (the result is already flat).
I'd use string interpolation "#{e}:#{f}"
2

My suggestion would be to split the problem into two separate problems. In this case, the following:

  1. iterate through each element on both arrays at once. pushing in the values as we go.
  2. place the string into a branch new array.

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.

3 Comments

It works, but it is not a Ruby way. It is the old school way. I won't downvote, but I won't upvote either.
never said it was, hence me saying at the very end that there is surely a better way to do this. And this is the case, as demonstrated by Phil.
I posted before I saw the answer Phil gave, by the time I posted, Phil had also posted. Therefore, my page updated with both my answer and Phil's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.