From: Brian Candler Date: 2010-06-23T18:57:07+09:00 Subject: Re: Iterate over specific keys in a hash 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/.