All posts tagged ruby

Dividing numbers in Ruby returning zero or an integer unexpectedly?

There’s a “quirk” about Ruby that I often forget when going back to it after a long period of time using other languages. If you divide two integers in Ruby then it’s going to give you an integer as a result. Consider the following:

some_int = 3
another_int = 2
answer = some_int / another_int  # answer is going to be 1 here

To fix this you’ll need to convert your integers to floats first. The following will work:

some_int = 3
another_int = 2
answer = some_int.to_f / another_int.to_f  # answer is going to be 1.5 here

the to_f function is going to convert the integers to floats and give you the float (decimal) answer.