gpt4 book ai didi

ruby - 为什么将字符串铲入哈希会导致此结果?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:39 25 4
gpt4 key购买 nike

<分区>

我正在研究 Ruby Koans,以便更好地掌握 Ruby 和 TDD。我到达了 about_hashes.rb 中代码的第 93 行,这让我感到困惑,它如何被铲到默认构造函数而不是散列值中。出于好奇,我尝试使用与字符串相同的东西作为构造函数的参数,它产生了类似的结果。

现在我的问题是,为什么无论我使用什么键,都会检索到相同的对象,以及我如何将新对象铲到方法中散列中特定键的数组中 test_default_value_is_the_same_object?

def test_default_value_is_the_same_object
hash = Hash.new([])

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

assert_equal ["uno", "dos"], hash[:one] #why not ["uno"]?
assert_equal ["uno", "dos"], hash[:two] #why not ["dos"]?
assert_equal ["uno", "dos"], hash[:three] #why not []?

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

def test_default_value_with_block
hash = Hash.new {|hash, key| hash[key] = [] }

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

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

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