Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the formatting/syntax for assert_equal hashes different than other assert_equals?

Tags:

syntax

ruby

I'm working my way through the Ruby Koans and am currently on AboutHashes. Up to this point the assert_equals have followed a specific formatting style of: assert_equal space expected_value comma actual value (e.g., assert_equal 2, 1 + 1). But the test_creating_hashes def in About Hashes has an assert_equal that doesn't follow this pattern, and if I change it to match that pattern it fails. Specifically:

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

So what's special about the assert_equal in this situation?

The meat of the test failure message is:

<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>'
like image 538
MacSean Avatar asked Apr 14 '11 01:04

MacSean


1 Answers

It fails because Ruby parses the first example as passing in an empty block {}, not an empty hash. I wouldn't be surpised if it gave a SyntaxError (see below).

However by explicitly putting the parenthesis, you are telling ruby "these are the arguments I want to pass into this method".

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
like image 147
Mike Lewis Avatar answered Oct 07 '22 02:10

Mike Lewis