In Ruby, what's the advantage of #each_pair over #each when iterating through a hash?
Asked Answered
A

1

21

Let's say I want to access the values of a hash like this:

munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}

I could use #each with two parameters:

munsters.each do |key, value| 
    puts "#{name} is a #{value["age"]}-year-old #{value["gender"]}."
end

Or I could use #each_pair with two parameters:

munsters.each_pair do |key, value| 
    puts "#{name} is a #{value["age"]}-year-old #{value["gender"]}."
end

Perhaps the difference between the two is not borne out in this simple example, but can someone help me to understand the advantage of using #each_pair over #each ?

Analgesic answered 26/9, 2017 at 20:47 Comment(1)
@lurker you can do the same with #each_pair.Florella
H
43

Because Hash is an Enumerable, it has to have an each method. each_pair may be a clearer name, since it strongly suggests that two-element arrays containing key-value pairs are passed to the block.

They are aliases for each other: they share the same source code.

Herrin answered 26/9, 2017 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.