Dynamic Division in Ruby

While writing one of my first Ruby projects I cam across an interesting behavior that initially had me confused. Ruby being a dynamic language, you aren’t declaring specific types so there is a degree of trust in the ruby interpreter. I was doing some simple mathematical formulas but when I ran my unit tests the result were wrong. It turns out that when you divide two integer values the default result type is an integer.

puts 9 / 2 => 4

Looking into it there seem to be two ways to address this, the first is to convert one of the values to a float and the second is to use the quo() method.

puts 9.to_f / 2 => 4.5


puts 9.quo(2) => 9/2

The thing with the last example is that the quo() method on a Fixnum type returns a rational type. Not sure about the benefits of a float v’s a rational so I will leave that choice to you.

One of the consequences of this is a re-emphasising of the importance of unit testing ruby code. If you have a method that does division you will need to include test that ensure that it will support both fixnum and float types.


def divTest(val1, val2) val1 / val2 end puts divTest(9, 2) => 4 puts divTest(9.0, 2) => 4.5 puts divTest(9.to_f, 2) => 4.5

In this case you can see that the method returns different results based on the type of numeric value that is being passed in. One of those learning curve bumps that you can burn a bit of time on.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: