1

Given certain keys, I want to get an array of values from a hash (in the order I gave the keys). I had done this:

class Hash

  def values_for_keys(*keys_requested)
    result = []
    keys_requested.each do |key|
      result << self[key]
    end
    return result
  end

end

I modified the Hash class because I do plan to use it almost everywhere in my code.

But I don't really like the idea of modifying a core class. Is there a builtin solution instead? (couldn't find any, so I had to write this).

1
  • you could also write a utility class where ur function will take hash and keys as params. Commented Aug 5, 2013 at 4:55

2 Answers 2

5

You should be able to use values_at:

values_at(key, ...) → array

Return an array containing the values associated with the given keys. Also see Hash.select.

h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
h.values_at("cow", "cat")  #=> ["bovine", "feline"]

The documentation doesn't specifically say anything about the order of the returned array but:

  1. The example implies that the array will match the key order.
  2. The standard implementation does things in the right order.
  3. There's no other sensible way for the method to behave.

For example:

>> h = { :a => 'a', :b => 'b', :c => 'c' }
=> {:a=>"a", :b=>"b", :c=>"c"}
>> h.values_at(:c, :a)
=> ["c", "a"]
Sign up to request clarification or add additional context in comments.

Comments

0

i will suggest you do this:

your_hash.select{|key,value| given_keys.include?(key)}.values

Comments

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.