简体   繁体   中英

Iterating over a Hash in Ruby. Difference between these two examples?

I am trying to learn a little Ruby. Can someone please explain to me the difference between these two examples?

Say that I have a hash:

family = { "Homer" => "dad",
  "Marge" => "mom",
  "Lisa" => "sister",
  "Maggie" => "sister",
  "Abe" => "grandpa",
  "Santa's Little Helper" => "dog"
}

If I iterate like this:

family.each { |x| puts "#{x}" }

I get this:

["Homer", "dad"]
["Marge", "mom"]
["Lisa", "sister"]
["Maggie", "sister"]
["Abe", "grandpa"]
["Santa's Little Helper", "dog"]

When I iterate like this:

family.each { |x, y| puts "#{x}: #{y}" }

I get this:

Homer: dad
Marge: mom
Lisa: sister
Maggie: sister
Abe: grandpa
Santa's Little Helper: dog

Can someone please explain how the two results differ (what do the square brackets, quotes, commas, colons mean?), and when one might use one vs. the other? Thank you!

When you iterate a hash, it passes the key , value pair as a parameter in the format of an array of two elements: [key, value] . That is the reason you are seeing ["Homer", "dad"] in your first example, x is being assigned with the array.

The second example is the same but in that case you are assigning the pair to x and y . x gets the first element of the array and y the second element, that is called multiple assignment in ruby.

2.2.2 :001 > x = {a: 1}.first
 => [:a, 1] 
2.2.2 :002 > x
 => [:a, 1] 
2.2.2 :003 > x,y ={a: 1}.first
 => [:a, 1] 
2.2.2 :004 > x
 => :a 
2.2.2 :005 > y
 => 1 

In your first example, you're iterating over each complete element of the hash ( x ), and printing it as a single key:value pair, resulting in the bracketed format.

In your second example, you're iterating over each element in the hash again, but specifically splitting that element into the key and value ( x , y ) being fed into the puts statement, and printing them with your own formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM