[英]Iterating over a Hash in Ruby. Difference between these two examples?
I am trying to learn a little Ruby. 我正在尝试学习一点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]
. 迭代哈希时,它将以两个元素的数组格式传递key
value
对作为参数: [key, value]
。 That is the reason you are seeing ["Homer", "dad"]
in your first example, x
is being assigned with the array. 这就是在第一个示例中看到["Homer", "dad"]
的原因, x
被分配了数组。
The second example is the same but in that case you are assigning the pair to x
and y
. 第二个示例是相同的,但是在这种情况下,您要将该对分配给x
和y
。 x
gets the first element of the array and y
the second element, that is called multiple assignment in ruby. x
获取数组的第一个元素, y
获取第二个元素,在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. 在第一个示例中,您要遍历哈希( x
)的每个完整元素,并将其打印为单个key:value对,从而得到方括号格式。
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. 在第二个示例中,您将再次遍历哈希中的每个元素,但具体地是将该元素拆分为要放入puts
语句中的键和值( x
, y
),并使用自己的格式进行打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.