Ruby Koans的test_changing_hashes中的附加问题的答案是什么?

sigwle7e  于 2023-03-22  发布在  Ruby
关注(0)|答案(4)|浏览(106)

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

我想不出注解中的附加问题的答案-我实际上尝试了他们建议的替换,结果是一样的。我能想出来的是,这是为了可读性,但我没有看到像本教程其他地方那样的通用编程建议。
(我知道这听起来像是已经在某个地方回答过的问题,但我找不到任何权威的答案。

zbwhf8kr

zbwhf8kr1#

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

assert_equal { :one => "eins", :two => "dos" }, hash

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

gkn4icbw

gkn4icbw2#

我认为它更易读,但你仍然可以这样做:

assert_equal true, { :one => "eins", :two => "dos" } == hash
h7wcgrx3

h7wcgrx33#

您可以使用的另一个测试如下:

assert_equal hash, {:one => "eins", :two => "dos"}

我只是将参数交换为assert_equal。在这种情况下,Ruby不会抛出异常。
但这对我来说仍然是一个糟糕的解决方案,使用一个单独的变量并测试一个布尔条件会更容易阅读。

pftdvrlh

pftdvrlh4#

我将变量expected与hash进行比较,而不是broke
期望值= {:one =〉'eins',:two =〉“dos”}

需要assert_equal,hash

相关问题