kty0mka
kty0mka

Reputation: 13

Ruby: compile a hash from two 2d arrays with appropriate combinations

I have two 2d arrays:

product_names_array = [product_one_names = ["Product One A", "Product One B"],
                      product_two_names = ["Product Two C", "Product Two D"]]
product_prices_array = [product_one_price = [product_one_price_1, product_one_price_2, product_one_price_3, product_one_price_4],
                        product_two_price = [product_two_price_1, product_two_price_2, product_two_price_3, product_two_price_4]]

In the first 2D array, I have 2 sub-arrays (in reality there are 16 of them) - one for each product. Each of them lists different names for the same product (each product can have from 1 to 22 alternative names).

In the second 2D array, I have 2 sub-arrays (in reality there are also 16 of them) - one per price list for each product. Each of them lists different prices (in reality, 10 price options) of the same product (which may have several names) from the corresponding sub-array in the previous 2D array.

From arrays I want to make such a hash:

my_hash = {"Product One A" => [product_one_price_1, product_one_price_2, product_one_price_3, product_one_price_4],
          "Product One B" => [product_one_price_1, product_one_price_2, product_one_price_3, product_one_price_4],
          "Product One C" => [product_two_price_1, product_two_price_2, product_two_price_3, product_two_price_4],
          "Product Two D" => [product_two_price_1, product_two_price_2, product_two_price_3, product_two_price_4]}

As you can see, each value from the arrays in the first 2D array creates all possible combinations with each corresponding array in the second 2D array.

Then I want to use the created hash like this:

puts my_hash["Product One B"[2]] # => product_one_price_3

(I doubt the correctness of this expression, so I will be grateful if you will help me here too...)

I would also like to avoid defining new methods, because this code will be used in the plugin Computed Custom Field for Redmine, and it does not accept def.

I have already re-read a bunch of information about arrays and hashes in Ruby, well, so far I have not even come close to solving my problem. Any help would be helpful!

Upvotes: 0

Views: 83

Answers (1)

Fabio
Fabio

Reputation: 32455

You can benefit from zip method, which will combine corresponding elements from two arrays
([0] - [0], [1] - [1] and so on)

result = product_names_array.zip(product_prices_array)
  .flat_map { |names, prices| names.map { |name| [name, prices] }}
  .to_h

result

# output
# product_one_prices: 11, 12, 13, 14
# product_two_prices: 21, 22, 23, 24
{
  "Product One A"=>[11, 12, 13, 14], 
  "Product One B"=>[11, 12, 13, 14], 
  "Product Two C"=>[21, 22, 23, 24], 
  "Product Two D"=>[21, 22, 23, 24]
}

Upvotes: 1

Related Questions