我正在研究 Ruby Koans,以便更好地掌握 Ruby 和 TDD。我到达代码中的第 93 行about_hashes.rb
这让我很困惑如何将其铲入默认构造函数而不是哈希值中。出于好奇,我尝试使用相同的字符串作为构造函数的参数,它产生了类似的结果。
现在我的问题是,为什么无论我使用什么键,都会检索到相同的对象,以及如何将新对象铲入方法中哈希中特定键的数组中 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
测试的名称暗示了其原因。
test_default_value_is_the_same_object
是否可以向您展示当您提出要求时hash[:some_value_that_doesnt_exist_yet]
,默认情况下,你会得到你指定的默认值——这是同一个物体每次。通过修改该对象,您可以为每个不存在的键修改它。修改hash[:one]
还修改hash[:two]
.
test_default_value_with_block
显示了使用块构建哈希,该块将用于为每个键提供新值。当你这样做时,值hash[:one]
and hash[:two]
是不同的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)