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.
You are creating a Rational number with 3/4 as the only argument. 3/4 is 0, so, your code is equivalent to
Rational
3/4
0
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.
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
Copyright © 2021 Jogjafile Inc.
You are creating a
Rationalnumber with3/4as the only argument.3/4is0, so, your code is equivalent towhich obviously is
0.Compare this to
where you explicitly pass both the numerator and denominator.