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
2010-08-09 17:40:43
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
2010-08-09 17:41:11
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
2010-08-09 17:49:48