0

I have two arrays one = [1,2,3,4,5,6,7] and two = [{1=>'10'},{3=>'22'},{7=>'40'}]

Two will have one.length hashes or less. I want a new array of values from two if it's key appears in one, if not then use 0. The new array would be [10,0,22,0,0,0,40] What is the best way to do this?

2
  • 1
    Your two is invalid. Commented Mar 12, 2014 at 13:37
  • 3
    That is also invalid. Commented Mar 12, 2014 at 13:44

2 Answers 2

9

I'd do it using Enumerable#reduce and Hash#values_at:

two.reduce({}, :merge).values_at(*one).map(&:to_i)
# => [10, 0, 22, 0, 0, 0, 40]
Sign up to request clarification or add additional context in comments.

Comments

4
h = [{1 => '10'}, {3 => '22'}, {7 => '40'}].inject(:merge).to_h
one.map{|e| h[e].to_i}
# => [10, 0, 22, 0, 0, 0, 40]

3 Comments

You should pass an empty hash as the first argument to inject, otherwise [].inject(:merge) # => nil and h[e] would raise a NoMethodError.
@toro2k Your point is correct, but I would rather do to_h. That looks prettier to me.
@sawa we can combine 2 answers two.inject(:merge).values_at(*one).map(&:to_i)

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.