Tuesday, September 11, 2007

When is / not division?

When you are using the wrong Ruby object.

Ruby seems innocent enough, but it's really doing a lot of 'object' work without you knowing.

Take the following rails example.

points = 0
points_possible = 100
points += quiz.points # points is 40, stored as an integer in the db,
percentage = ((points / points_possible) * 100) # evaluates to 0, WTF!

If we just give Ruby a little more direction by changing points to a float.

percentage = ((points.to_f / points_possible) * 100) # evaluates to 40, rock on

No comments: