gpt4 book ai didi

ruby - 为什么 assert_equal 哈希的格式/语法与其他 assert_equals 不同?

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

我正在研究 Ruby Koans目前正在使用 AboutHashes。到目前为止,assert_equals 遵循特定的格式样式:assert_equal space expected_value comma actual value (例如,assert_equal 2, 1 + 1)。但是 About Hashes 中的 test_creating_hashes def 有一个不遵循这种模式的 assert_equal,如果我更改它以匹配该模式,它就会失败。具体来说:

def test_creating_hashes
empty_hash = Hash.new
assert_equal {}, empty_hash # --> fails
assert_equal({}, empty_hash) # --> passes
end

那么在这种情况下 assert_equal 有什么特别之处呢?

测试失败消息的内容是:

<internal:lib/rubygems/custom_require>:29:in `require':    /Ruby_on_Rails/koans/about_hashes.rb:7: syntax error, unexpected ',', expecting keyword_end (SyntaxError)
assert_equal {}, empty_hash #{} are also used for blocks
^
from <internal:lib/rubygems/custom_require>:29:in `require'
from path_to_enlightenment.rb:10:in `<main>'

最佳答案

它失败了,因为 Ruby 将第一个示例解析为传入空 block {},而不是空哈希。如果它给出 SyntaxError(见下文),我不会感到惊讶。

然而,通过显式放置括号,您是在告诉 ruby​​ “这些是我想传递给此方法的参数”。

def t(arg1, arg2)
p arg1
end


ruby-1.9.2-p136 :057 > t {}
ArgumentError: wrong number of arguments (0 for 2)
ruby-1.9.2-p136 :056 > t {}, arg2
SyntaxError: (irb):56: syntax error, unexpected ',', expecting $end
t {}, arg2

关于ruby - 为什么 assert_equal 哈希的格式/语法与其他 assert_equals 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657733/

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