Frederick Cheung wrote in post #1020782:
> by default if you are working with integers you'll always get integers
> back (by truncation). If you want floating point numbers then you
> should convert the numbers you're working with to floating point
> numbers first (using to_f), so
>
> 5 /2 will always  return 2, but 5.0 / 2 will produce 2.5

This might also help to clarify what's happening:

$ irb
ruby-1.9.2-p290 :014 > x = 5
 => 5
ruby-1.9.2-p290 :015 > y = 3
 => 3
ruby-1.9.2-p290 :016 > z = x / y
 => 1
ruby-1.9.2-p290 :017 > x.class
 => Fixnum
ruby-1.9.2-p290 :018 > y.class
 => Fixnum
ruby-1.9.2-p290 :019 > z.class
 => Fixnum
ruby-1.9.2-p290 :020 > x = 5
 => 5
ruby-1.9.2-p290 :021 > y = 3.0
 => 3.0
ruby-1.9.2-p290 :022 > z = x / y
 => 1.6666666666666667
ruby-1.9.2-p290 :023 > x.class
 => Fixnum
ruby-1.9.2-p290 :024 > y.class
 => Float
ruby-1.9.2-p290 :025 > z.class
 => Float
ruby-1.9.2-p290 :026 > x = 5
 => 5
ruby-1.9.2-p290 :027 > y = 3
 => 3
ruby-1.9.2-p290 :028 > z = x.fdiv(y)
 => 1.6666666666666667
ruby-1.9.2-p290 :029 > x.class
 => Fixnum
ruby-1.9.2-p290 :030 > y.class
 => Fixnum
ruby-1.9.2-p290 :031 > z.class
 => Float
ruby-1.9.2-p290 :032 > z = x.quo(y)
 => (5/3)
ruby-1.9.2-p290 :033 > z.class
 => Rational
ruby-1.9.2-p290 :034 > z.to_f
 => 1.6666666666666667
ruby-1.9.2-p290 :035 > z.to_i
 => 1

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to