0

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.

steven_noble
  • 4,133
  • 10
  • 44
  • 77

2 Answers2

5

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
1

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