tags:

views:

55

answers:

3
+2  Q: 

Hash.each question

Hash.each return an array [key, value] but if i want an hash? Example: {:key => value }

+4  A: 

I'm assuming you meant "yields" where you said "return" because Hash#each already returns a hash (the receiver).

To answer your question: If you need a hash with the key and the value you can just create one. Like this:

hash.each do |key, value|
  kv_hash = {key => value}
  do_something_with(kv_hash)
end

There is no alternative each method that yields hashs, so the above is the best you can do.

sepp2k
A: 

Call .each with two parameters:

>> a = {1 => 2, 3 => 4}
>> a.each { |b, c|
?>     puts "#{b} => #{c}"
>>   }
1 => 2
3 => 4
=> {1=>2, 3=>4}
Chris Bunch
A: 

You could map the hash to a list of single-element hashes, then call each on the list:

h = {:a => 'a', :b => 'b'}
h.map{ |k,v| {k => v}}.each{ |x| puts x }
Gabe Moothart