Zack Shapiro
Zack Shapiro

Reputation: 6998

Why can't I divide a fixnum by another fixnum?

I'm currently trying to divide counts["email"] a hash containing the number 82,000 by a variable total which contains the value 1.3 million.

When I run puts counts["email"]/total I get 0.

Why can't I perform division on these?

Upvotes: 5

Views: 1813

Answers (3)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

You are performing division, although not the one you expected. There are many different ways to divide integers in Ruby:

# Integer division:
5 / 4     # => 1

# Floating point division:
5.fdiv(4) # => 1.25

# Rational division:
5.quo(4)  # => Rational(5, 4)

You can also convert one of your integers to a Float or a Rational:

5.to_f / 4 # => 1.25
5.to_r / 4 # => Rational(5, 4)

Note that first calling fdiv directly is faster than calling to_f and then using the / operator. It also makes it clear that you are using floating point division.

Upvotes: 9

raina77ow
raina77ow

Reputation: 106375

Because that's how Ruby works: when you divide integer to integer, you get an integer. In this case that'll be 0, because it's the integer part of the result.

To get the float result, just tell Ruby that you actually need a float! There're many ways to do it, I guess the most simple would be just convert one of the operand to Float...

puts counts["email"]/total.to_f

Upvotes: 7

tomferon
tomferon

Reputation: 5001

You need to use floats in order to get the "full" result.

counts["email"] / total.to_f

Upvotes: 0

Related Questions