gpt4 book ai didi

Ruby koans : How does the solution to about_hashes. rb 'test_default_value' 有意义吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:27 29 4
gpt4 key购买 nike

对于 Ruby koan 40,命令行告诉我这段代码中的下划线部分...

def test_default_value
hash1 = Hash.new
hash1[:one] = 1

assert_equal 1, hash1[:one]
assert_equal nil, hash1[:two]

hash2 = Hash.new("dos")
hash2[:one] = 1

assert_equal 1, hash2[:one]
assert_equal __, hash2[:two] # <<<< here's the underscore section
end

...应该是“dos”。在初始化 hash2 时没有指定键的情况下,Ruby 如何将“dos”分配给 :two 键?如果这有意义,我会感到非常惊讶。

但如果你能让我理解它,那就太好了!

最佳答案

hash2 使用默认值 "dos" 进行初始化。

hash2 = Hash.new("dos") 

因此,每次您访问未明确分配值的键时,您将返回“dos”。请注意,每个散列都有一个默认值。默认情况下,它只是 nil

默认值不是“分配的”。当访问一个散列值时,Ruby 试图首先找到一个在散列中明确设置的值。只有当没有找到时,它才返回默认值。

最后要说的是:在创建散列时还有另一种形式来设置默认值:

my_hash = Hash.new { |hash, key| hash[key] = "dos" }

一般来说,这里首选这种形式,每次访问一个不存在的键时,默认值都是一个新对象。如果您想就地更改默认值(在数组或其他哈希的情况下通常会这样做),这一点很重要。

对于简单的东西,这可能并不重要。只是为了以后记住:)

关于Ruby koans : How does the solution to about_hashes. rb 'test_default_value' 有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27821489/

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