Luan Truong
Luan Truong

Reputation: 124

Sum of BigDecimals ended up being Integer [Ruby on Rails]

I have recently encountered a problem where the sum of big decimals don't return a big decimal, but instead an integer.

sig { returns(BigDecimal) }
def period_hours
  @applicable_items.sum { |payroll_item| payroll_item.hours_worked.to_d }
end

Where @applicable_items return an array of PayrollItem.

The error that I got:

Return value: Expected type BigDecimal, got type Integer with value 0

Also, RubyMine also gives a warning that the return type is not compatible:

Incompatible types
Required:
BigDecimal
Returned:
Integer

I think I can easily get away by adding to_d at the end like this:

@applicable_items.sum { |payroll_item| payroll_item.hours_worked.to_d }.to_d

But still, I am just curious to know why this could possibly return Integer instead of BigDecimal while all the values of the sum are already converted using to_d.

Thank you so much!

Upvotes: 2

Views: 395

Answers (1)

smathy
smathy

Reputation: 27961

Like this:

irb(main):003:0> [].sum &:to_d
=> 0

Upvotes: 2

Related Questions