Question

Can someone please explain this to me?

x = Rational(3/4) * 8
 => (0/1) # I Expected it to return 6
x.to_i
 => 0 

Thanks.

Was it helpful?

Solution

You are creating a Rational number with 3/4 as the only argument. 3/4 is 0, so, your code is equivalent to

Rational(0) * 8

which obviously is 0.

Compare this to

Rational(3, 4) * 8
# => (6/1)

where you explicitly pass both the numerator and denominator.

OTHER TIPS

If you prefer having slashes in the fractions, you may use strings as arguments:

x = Rational('3/4') * 8

or

x = ('3/4'.to_r) * 8
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top