我正在通过
Ruby Koans的工作,目前在AboutHash上.到此为止,assert_equals遵循以下特定的格式化样式:assert_equal space expected_value逗号实际值(例如assert_equal 2,11).但是,关于Hash中的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将第一个示例解析为传递一个空块{},而不是空哈希.如果它给出了一个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,expecting $end t {},arg2