我正在Ruby Koans工作,现在正在关注哈希。到目前为止,assert_equals遵循特定的格式样式:assert_equal
space expected_value
逗号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>'
答案 0 :(得分:24)
失败是因为Ruby将第一个示例解析为传入空块{},而不是空哈希。如果它给出了一个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