Hash.new(0) vs. Hash.new { |h,k| h[k] = 0 }

While putting DRYing some tests, I am trying to initialize a hash as follows:

business = Business.new(0)

But this returns an error in testing. Specifically:

  1) Error: test_should_have_nils_not_zeroes_except_for_sales_tax_rate(BusinessTest): TypeError: can't dup Fixnum     /test/unit/business_test.rb:41:in `new'     /test/unit/business_test.rb:41:in `test_should_have_nils_not_zeroes_except_for_sales_tax_rate'

However, this works fine:

business = Business.new { |h,k| h[k] = 0 }

The hash business is an ActiveRecord class.

Any thoughts on what the heck is going on? Are the two situations different because ActiveRecord needs to create the hash first and the block assignment lets that happen and then assigns values?

Bill

I spoke too soon. Neither one appears to work.

Any thoughts on what the heck is going on? Are the two situations different because ActiveRecord needs to create the hash first and the block assignment lets that happen and then assigns values?

ActiveRecord objects aren't hashes - if you pass an argument to Business.new it's expecting a hash of attribute values.

Fred