Iterate over specific keys in a hash

S

Safas Khkjh

Hi,
I have a hash;

cars{ "car0" => "bmw", "car1" => "seat", "car3" => "mercedes", "car4" =>
"renault"}

What I want is to extract just the values of car0 and car3.

Is there a way instead of doing cars.each_value of doing
cars.each_value[0,3]?

Thank you in advance.

Ryan
 
B

Brian Candler

Safas said:
I have a hash;

cars{ "car0" => "bmw", "car1" => "seat", "car3" => "mercedes", "car4" =>
"renault"}

What I want is to extract just the values of car0 and car3.

Is there a way instead of doing cars.each_value of doing
cars.each_value[0,3]?

[cars["car0"], cars["car3"]]

I'm not sure what you would want [0,3] to do. For an Array, that would
mean start at 0th element, count for 3 elements, i.e. would give you
elements 0,1 and 2.

However, hashes are not indexed by integers. It's a property of hashes
in ruby 1.9 (only) that they maintain their insertion order when
iterating, but you still can't access the nth item directly.

So perhaps you want to use an Array instead:
cars = ["bmw", "seat", "mercedes", "renault"] => ["bmw", "seat", "mercedes", "renault"]
cars.values_at(0,3)
=> ["bmw", "renault"]
 
L

Luc Heinrich

Hi,
I have a hash;

cars{ "car0" => "bmw", "car1" => "seat", "car3" => "mercedes", "car4" =>
"renault"}

What I want is to extract just the values of car0 and car3.

cars.values_at("car0", "car3")
# => ["bmw", "mercedes"]
 
B

Brian Candler

Update: if you are interested at the values for particular keys, then
you can also do
bmw
mercedes
=> ["bmw", "mercedes"]

If you really want to rely on the insertion order, which I'd strongly
recommend against even under ruby 1.9, there's a brute-force way:

cars.each_value.with_index do |c,i|
next unless [0,3].include?(i)
puts c
end

Note that this will give you bmw and renault, because it ignores the
keys completely.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top