Ruby Koans的test_changing_hashes中的奖金问题的答案是什么?

Bru*_*uce 55 ruby

Ruby Koans中,about_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 was "expected" broken out into a variable
    # rather than used as a literal?
end
Run Code Online (Sandbox Code Playgroud)

我无法在评论中找出奖金问题的答案 - 我实际上尝试过他们建议的替换,结果是一样的.我可以理解的是,它是为了可读性,但我没有看到像本教程中其他地方所述的一般编程建议.

(我知道这听起来好像已经在某个地方得到了回答,但我无法挖掘任何权威的东西.)

Vas*_*ich 83

这是因为你不能使用这样的东西:

assert_equal { :one => "eins", :two => "dos" }, hash
Run Code Online (Sandbox Code Playgroud)

Ruby认为{...}是一个块.所以,你应该"把它分解成变量",但你总是可以使用assert_equal({ :one => "eins", :two => "dos" }, hash)

  • 这确实让它破裂了,再次感谢.我并不觉得太糟糕,因为Koans甚至没有向我介绍过"块"的概念. (2认同)
  • 答案是对的.Koans和OP不会像上面那样编写代码.如果它是字面意思,它将如下所示:`assert_equal true,{:one =>"eins",:two =>"dos"} == hash` (2认同)