Ruby .ceil and .floor

Everything is returned correctly.

puts 8/3.ceil == 2
#=> true, because 8/3 returns an Integer, 2
puts 8/3.floor == 2
#=> true, because 8/3 returns an Integer, 2
puts 2.67.ceil == 2
#=> false, because 2.67.ceil is 3
puts 2.67.floor == 2
#=> true, because 2.67.floor is 2

To make things of more sense here, you can convert results to Float:

(8.to_f / 3).ceil == 2  #=> false
(8.to_f / 3).floor == 2 #=> true
2.67.ceil == 2          #=> false
2.67.floor == 2         #=> true

Another thing to bear in mind, that having written 8/3.ceil is actually 8 / (3.ceil), because the . binds stronger than /. (thx @tadman)

Yet another thing to mention, is that (thx @Stefan):

There’s also fdiv to perform floating point division, i.e.
8.fdiv(3).ceil. And Ruby also comes with a nice Rational class: (8/3r).ceil.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)