I use Rails to generate JSON for a javascript charting library (High Charts). There are a few places where I use integer arithmetic to calculate percentages in bar charts like this (simplified example):
def to_json
data.map{|numerator, denominator| numerator * 100 / denominator }
end
This server has been running without problems for several years but, just in the last couple of weeks, this has started to fail occasionally because it generates a Rational
number instead of a Fixnum
(eg. 2700/50
instead of 54
). This breaks because the JSON parser in the browser does not understand the rational number.
The fix is easy (call to_i
or round
on the result) but I am confused as to why this suddenly started happening after 4 years and why it only happens on some Passenger instances on a single server on my web farm. The web machines are identical (as far as I know).
My four part question:
- Is there a more idiomatic way to compute percentages in Ruby?
- What are the rules for when Ruby generates a rational rather than a fixnum?
- Why did this suddenly start happening?
- Why would it only happen on some instances of my rails server?
Version details:
- ruby 2.2.2
- Rails 3.2.22
- passenger-5.0.21
- Ubuntu 12.04.5 LTS