在测试Ruby Koan的哈希值时,奖金问题的答案是什么?
在中,关于_hashes.rb的部分包括以下代码和注释:在测试Ruby Koan的哈希值时,奖金问题的答案是什么?,ruby,Ruby,在中,关于_hashes.rb的部分包括以下代码和注释: def test_changing_hashes hash = { :one => "uno", :two => "dos" } hash[:one] = "eins" expected = { :one => "eins", :two => "dos" } assert_equal true, expected == hash # Bonus Question: Why
def test_changing_hashes
hash = { :one => "uno", :two => "dos" }
hash[:one] = "eins"
expected = { :one => "eins", :two => "dos" }
assert_equal true, expected == hash
# Bonus Question: Why was "expected" broken out into a variable
# rather than used as a literal?
end
我无法在评论中找到奖金问题的答案——我尝试了他们建议的替代品,结果是一样的。我所能理解的是,它是为了可读性,但我看不到像本教程其他地方提到的一般编程建议
(我知道这听起来像是某个地方已经有了答案,但我找不到任何权威。)这是因为你不能使用这样的东西:
assert_equal { :one => "eins", :two => "dos" }, hash
assert_equal true, { :one => "eins", :two => "dos" } == hash
Ruby认为
{…}
是一个块,所以它应该“分解成一个变量”,但是您可以始终使用断言相等({:one=>“eins”,:two=>“dos”},hash)
可以使用的另一个测试如下:
assert_equal hash, {:one => "eins", :two => "dos"}
我只是将参数交换为assert\u equal
。
在这种情况下,Ruby不会抛出异常
但对我来说,这仍然是一个糟糕的解决方案。使用单独的变量和测试布尔条件更具可读性。我认为它更具可读性,但您仍然可以这样做:
assert_equal { :one => "eins", :two => "dos" }, hash
assert_equal true, { :one => "eins", :two => "dos" } == hash
我完全喜欢这个答案,除了当我真的尝试按照您的建议替换哈希时,它仍然工作正常,断言通过了。编辑-不,我没有-我做了较小的更改,将断言与“true”进行比较。我会试试你的建议,这样我就可以看着它破裂了谢谢这确实让它破裂了,再次感谢。我并不觉得太糟糕,因为Koans甚至还没有向我介绍“块”的概念。(这里是ruby noob)既然我们已经改变了使用变量,为什么我们不直接使用(assert_equal expected,hash)而使用(assert_equal true,expected==hash)?这个答案是错误的。Koans和OP不会像上面那样编写代码。如果它是文字,它将如下所示:
assert_equal true,{:one=>“eins”,“two=>“dos”}==hash
我假设你实际上是指assert_equal hash,{:one=>“eins”,“two=>“dos”}
,它的缺点是不显示实际值,并且比assert hash==={:one=>“eins”,:two=>“dos”}
(我怀疑但不知道必须像我所做的那样颠倒顺序。)