为什么Ruby Koans练习的about_hashes.rb中的test_default_value_is_the_same_object有数组的答案? [英] Why does the test_default_value_is_the_same_object in about_hashes.rb of Ruby Koans exercises have the answer of an array?

查看:41
本文介绍了为什么Ruby Koans练习的about_hashes.rb中的test_default_value_is_the_same_object有数组的答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做 ruby​​ koans 练习,我对为什么 test_default_value_is_the_same_object 方法练习中的答案是这样的感到有些困惑.代码如下:

I'm doing the ruby koans exercises and am a bit confused about why the answers are such in the test_default_value_is_the_same_object method exercises. Below is the code:

def test_default_value_is_the_same_object
hash = Hash.new([])

hash[:one] << "uno"
hash[:two] << "dos"

assert_equal ["uno", "dos"], hash[:one]
assert_equal ["uno", "dos"], hash[:two]
assert_equal ["uno", "dos"], hash[:three]
end

我不知道为什么不管键是什么,值总是uno"和dos"?我想当key是one时,返回的值应该是uno";当key为two"时,返回值应为dos".为什么不管key是什么,value总是一个数组?

I'm not sure why no matter what the key is, the value is always "uno" and "dos"? I thought when the key is one, the returned value should be "uno"; when key is "two", the returned value should be "dos". Why no matter what the keys are, the value is always an array?

谢谢您,期待您的答复!

Thank you and I'm looking forward to your answer!

推荐答案

hash = Hash.new([])

将使用 [] 实例化一个新数组(我们称之为 Harvey),然后以 Harvey 为默认值进行散列.

Will instantiate a new array with [] (let's call it Harvey), then make a hash with Harvey as its default.

hash[:one]

不存在,所以你得到了 Harvey.Harvey 使用 Array#<< 运算符(等效于 harvey.push("one"))将 "uno" 添加到他身上)

doesn't exist, so you get Harvey. Harvey gets "uno" added to him, using the Array#<< operator (equivalent to harvey.push("one"))

hash[:two]

也不存在,所以你又得到了 Harvey(记住,他已经包含了 "uno").他现在也得到 "dos".

also doesn't exist, so you get Harvey again (who, remember, already contains "uno"). He now also gets "dos".

hash[:three]

返回 Harvey,仍然带着他的 "uno""dos".

returns Harvey, still with his "uno" and "dos".

如果您希望代码表现得像您认为应该的那样,在每个键中使用不同的数组,则每次需要默认值时都需要返回一个新数组,而不是每次都返回 Harvey:

If you wanted the code to behave like you think it should, with a different array in each key, you need to return a new array every time you want a default, not Harvey every single time:

hash = Hash.new { |h, k| h[k] = [] }

如果你只是希望散列与数组无关,请忽略 Harvey,并使用 Hash#[]= 而不是 Array#<<:

And if you just want the hash to have nothing to do with arrays, ignore Harvey, and use Hash#[]= instead of Array#<<:

hash = Hash.new()

hash[:one] = "uno"
hash[:two] = "dos"

这篇关于为什么Ruby Koans练习的about_hashes.rb中的test_default_value_is_the_same_object有数组的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆