Title Image
Twitter Logo
http://tiny.cc/cznl3 gotta love Harry. 5 days ago
Follow me on twitter @stewartmatheson

Dividing numbers in Ruby

15th
10 / 2009

Today like other days I was working on a game in ruby. Like any game this game uses a lot of rand(). Writing code for this game I came across this little quirk/feature of ruby. When dividing two integers ruby will return an integer. EG…

>> 10 / 2
=> 5

Thats fine but what about the following…

>> 100 / 56
=> 1

Ruby in this case did not return a float like I expected. It returned a rounded integer. To get a float make sure your dividing two floats.

>> 100.to_f / 56.to_f
=> 1.78571428571429

Thats more what I expected. So maybe you already worked this out but it was a slight trip up for me.