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
Comments
In fact, Hash#each and Hash#each_pair are aliases for each other. Take a look in the Ruby source code:
https://ruby-doc.org/core-2.5.0/Hash.html#method-i-each
https://ruby-doc.org/core-2.5.0/Hash.html#method-i-each_pair
static VALUE
rb_hash_each_pair(VALUE hash)
{
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
if (rb_block_arity() > 1)
rb_hash_foreach(hash, each_pair_i_fast, 0);
else
rb_hash_foreach(hash, each_pair_i, 0);
return hash;
}
hash = {1 => ‘one’, 2 => ‘two’, 3 => ‘three’}
hash.each { |e| puts e.inspect }
[1, “one”]
[2, “two”]
[3, “three”]
hash.each_pair { |e| puts e.inspect }
[1, “one”]
[2, “two”]
[3, “three”]