Today I Learned

hashrocket A Hashrocket project

Do float division with `fdiv`

Usually in ruby, when I need to perform floating point division I call .to_f on either the numerator or denominator, like this:

1 / 5.to_f
# 0.2

While many people might read this as floating point division instead of integer division, reading it that way gets trickier when those numbers are variables and the .to_f happens somewhere else.

You can be more explicit about the operation you are performing with .fdiv.

1.fdiv(5)
# 0.2

This works with floats as well, so that you can use fdiv in any context.

1.to_f.fdiv(5.to_f)
# 0.2
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.