Ruby中的默认哈希值(Rubykoans.com->;about_hashes.rb)
我正在浏览来自的关于_hashes.rb的文章。1个练习让我感到困惑:Ruby中的默认哈希值(Rubykoans.com->;about_hashes.rb),ruby,hash,Ruby,Hash,我正在浏览来自的关于_hashes.rb的文章。1个练习让我感到困惑: def test_default_value hash1 = Hash.new hash1[:one] = 1 assert_equal 1, hash1[:one] #ok assert_equal nil, hash1[:two] #ok hash2 = Hash.new("dos") hash2[:one] = 1 assert_equal 1, hash
def test_default_value
hash1 = Hash.new
hash1[:one] = 1
assert_equal 1, hash1[:one] #ok
assert_equal nil, hash1[:two] #ok
hash2 = Hash.new("dos")
hash2[:one] = 1
assert_equal 1, hash2[:one] #ok
assert_equal "dos", hash2[:two] #hm?
end
我猜Hash.new(“dos”)使“dos”成为所有不存在键的默认答案。我说得对吗?是的,你说得对,看起来ruby koans中有个错误,
hash2[:two]
将返回“dos”
请看一下方法文档
新的→ 新的\u散列新(obj)→ 新的\u散列
新的{散列,键{块}→ 新杂凑 返回一个新的空哈希。如果该散列随后被 与哈希项不对应的键,返回的值 取决于用于创建哈希的新文件的样式。首先 窗体,则访问返回nil如果指定了obj,则此单个对象 将用于所有默认值。如果指定了块,它将 使用哈希对象和键调用,并应返回 默认值。区块负责将值存储在 如果需要,可以使用散列
旁注:在这种情况下,您可以通过运行实际代码或在或(我推荐pry)中执行几行来确认您的期望。koan的原始版本是:
def test_default_value
hash1 = Hash.new
hash1[:one] = 1
assert_equal __, hash1[:one]
assert_equal __, hash1[:two]
hash2 = Hash.new("dos")
hash2[:one] = 1
assert_equal __, hash2[:one]
assert_equal __, hash2[:two]
end
错误不在koan中,而是在您已完成的断言中:
assert_equal nil, hash2[:two] #hm?
…应该是
assert_equal "dos", hash2[:two] #hm?