Hash#each vs. Hash#each_pair
by kiawin
Sometimes I find each and each_pair kind of confusing. Though Ruby’s API Doc has been one of the most well documented API Doc, it is not very helpful in showing the difference between each and each_pair.
Peeps from ruby-forum.com gave an excellent explanation:
#!/usr/bin/ruby
hash = {1 => 'one', 2 => 'two', 3 => 'three'}
p "p hash : #{hash}"
p "hash.each"
hash.each do |e| #e is [key,value]
p e
end
p "hash.each_pair"
hash.each_pair do |k,v| #k and v class as in hash
p "#{k}=#{v}"
end
p "hash.each_value"
hash.each_value do |e| #e is value
p e
end