Iterate over specific keys in a hash

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

···

--
Posted via http://www.ruby-forum.com/.

Safas Khkjh wrote:

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"]

···

--
Posted via http://www.ruby-forum.com/\.

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

···

On 23 juin 2010, at 11:23, Safas Khkjh wrote:

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.

--
Luc Heinrich - luc@honk-honk.com

Update: if you are interested at the values for particular keys, then
you can also do

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

"renault"}

cars.values_at("car0","car3").each { |c| puts c }

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.

···

--
Posted via http://www.ruby-forum.com/\.

Brian Candler;

Thank you very much! The following was exactly what I needed;

···

cars.values_at("car0","car3").each { |c| puts c }

--
Posted via http://www.ruby-forum.com/\.