Search code examples
rubyruby-on-rails-4pry-rails

Rails is showing incorrect calculation


[8] pry(#<Plan>)> self[:total_outstanding]||0 / self.dd_amount 
=> 10100.0
[9] pry(#<Plan>)> self[:total_outstanding]||0
=> 10100.0
[10] pry(#<Plan>)> self.dd_amount
=> 900.0
[11] pry(#<Plan>)> self[:total_outstanding].to_i||0/self.dd_amount.to_i
=> 10100

self[:total_outstanding].to_i||0/self.dd_amount.to_i should reuturn 11 instead of 10100 which the value of the first attribute

I am trying to debug this in a pry session

When the code ran it did consider the value as 10100 which is just wrong..


Solution

  • The OR operator (||) has lower precedence than the division operator (/).

    Ruby is interpreting your last line as this:

    self[:total_outstanding].to_i || (0/self.dd_amount.to_i)
    

    This will just return self[:total_outstanding].to_i, because it is a truthy value.

    Group self[:total_outstanding].to_i||0 together like this:

    (self[:total_outstanding].to_i||0) / self.dd_amount.to_i