gpt4 book ai didi

ruby - 铲子 (<<) 运算符在 Ruby Hashes 中如何工作?

转载 作者:数据小太阳 更新时间:2023-10-29 06:21:23 25 4
gpt4 key购买 nike

我正在浏览 Ruby Koans tutorial series ,当我在 about_hashes.rb 中遇到这个时:

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]

assert_equal true, hash[:one].object_id == hash[:two].object_id
end

assert_equals 中的值,实际上是教程所期望的。但我无法理解使用 << 之间有何区别运算符和 =运营商?

我的期望是:

  • hash[:one]将是 ["uno"]
  • hash[:two]将是 ["dos"]
  • hash[:three]将是 []

谁能解释一下为什么我的预期是错误的?

最佳答案

您有点混淆了它的工作方式。首先,哈希没有 <<方法,您示例中的该方法存在于数组中。

您的代码没有出错的原因是您通过构造函数将默认值传递给哈希。 http://ruby-doc.org/core-1.9.3/Hash.html#method-c-new

hash = Hash.new([])

这意味着如果一个键不存在,那么它将返回一个数组。如果您运行以下代码:

hash = {}
hash[:one] << "uno"

然后你会得到一个未定义的方法错误。

因此在您的示例中,实际发生的是:

hash = Hash.new([])

hash[:one] << "uno" #hash[:one] does not exist so return an array and push "uno"
hash[:two] << "dos" #hash[:two] does not exist, so return the array ["uno"] and push "dos"

它之所以没有像您预期的那样每次都返回一个只有一个元素的数组,是因为它存储了对您传递给构造函数的值的引用。这意味着每次推送一个元素时,它都会修改初始数组。

关于ruby - 铲子 (<<) 运算符在 Ruby Hashes 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com