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:intest_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.

On Oct 18, 2:28 pm, Bill D. [email protected]
wrote:

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

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

Fred

Thanks for the information. I’ve decided (at least for the time being)
to keep my tests painfully expressive and slightly less DRY than other
code. It can be hard to look as setting a list of attributes to 0 or an
empty string but it works.

Bill