3

I have 2 Arrays.

product_name = ["Pomegranate", "Raspberry", "Miracle fruit", "Raspberry"]
product_quantity =  [2, 4, 5, 5]

I'd like to know how to initialize a hash such that it becomes

product_hash = {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}

4 Answers 4

4

Use each_with_object:

product_name.zip(product_quantity)
            .each_with_object({}) {|(k, v), h| h[k] ? h[k] += v : h[k] = v }
#=> {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}

Or just use hash with default value:

product_name.zip(product_quantity)
            .each_with_object(Hash.new(0)) {|(k, v), h| h[k] += v }
#=> {"Pomegranate"=>2, "Raspberry"=>9, "Miracle fruit"=>5}
Sign up to request clarification or add additional context in comments.

3 Comments

No need for default proc when the defaut is immutable.
I meant to say that you can just write Hash.new(0)
@Eric, yes, sure. Edited.
1

I would start with something like this:

product_name.zip(product_quantity)
            .group_by(&:first)
            .map { |k, v| [k, v.map(&:last).inject(:+)] }
            .to_h
#=> { "Pomegranate" => 2, "Raspberry" => 9, "Miracle fruit" => 5}

I suggest to lookup each method in the Ruby's docs for Array and Hash and to check in the console what each the intermediate step returns.

Comments

1

This is but a slight variation of @llya's solution #2.

product_name.each_index.with_object(Hash.new(0)) { |i,h|
  h[product_name[i]] += h[product_quantity[i]] }            .

Comments

-1

Couldn't we just do:

product_name.zip(product_quantity).to_h

Seems to return the correct result for me?

3 Comments

It doesn't sum the "Raspberry", whose total quantity is 9. Your solution returns 5.
My bad :( DId not see that there were duplicated entries
Consider deleting your answer to avoid more downvotes.

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.