Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 978
clockworkpc Avatar asked Sep 26 '17 20:09

clockworkpc


People also ask

What is Ruby advantages and disadvantages of Ruby?

Ruby is a good language for application development, but some of its downsides lead companies to use other alternatives. There are many cases for using Ruby such as web scraping, automation, DevOps tools, and command-line media players, where PHP can fail.

What is disadvantage of Ruby on Rails?

Wrong architecture decisions during the initial stages of your project might cost you more in Rails than in any other framework. Since prototyping with Rails is incredibly fast, an engineering team inexperienced in Rails might make unobvious mistakes that will erode your application's performance in the future.

What is identifiers in Ruby?

Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby. Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ).


1 Answers

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.

like image 55
steenslag Avatar answered Sep 19 '22 17:09

steenslag