Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top