tapioco123
tapioco123

Reputation: 3545

Hash.each doesn't return a hash?

Hash.each returns an array [key, value], but if I want a hash?

Example: {:key => value }

Upvotes: 1

Views: 1164

Answers (4)

eloyesp
eloyesp

Reputation: 3285

I think you are trying to transform the hash somehow, so I will give you my solution to this problem, which may be not exactly the same. To modify a hash, you have to .map them and construct a new hash.

This is how I reverse key and values:

h = {:a => 'a', :b => 'b'}
Hash[h.map{ |k,v| [v, k] }]
# => {"a"=>:a, "b"=>:b}

Upvotes: 1

Gabe Moothart
Gabe Moothart

Reputation: 32112

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 }

Upvotes: 0

Chris Bunch
Chris Bunch

Reputation: 89923

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}

Upvotes: 0

sepp2k
sepp2k

Reputation: 370455

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.

Upvotes: 5

Related Questions