我正在学习Ruby Koans,目前使用的是AboutHashes。到目前为止,assert_equals遵循了一种特定的格式样式:assert_equal space expected_value comma actual value (例如,assert_equal 2, 1 + 1)。但是About散列中的test_creating_hashes定义有一个不遵循此模式的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>'发布于 2011-04-14 10:12:30
它之所以失败,是因为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 {}, arg2https://stackoverflow.com/questions/5657733
复制相似问题