Useful Methods in Float Class in Ruby

RubyServer Side ProgrammingProgramming

The Float class in Ruby is a subclass of the Numeric class. Its objects are the representations of real numbers, using the native architecture representation of floating-point numbers.

Let's consider the different methods that are available in the float class in Ruby.

== Method in Ruby

The == method is used when we want to return True, if two objects are equal.

Example

Consider the code shown below.

puts 3.7 == 4
puts 3.7 == 3.7

Output

It will produce the following output.

false
true

abs Method in Ruby

The abs method is used when we want to return the absolute value of a float.

Example

Consider the code shown below.

puts (-50.56).abs
puts (-69.04).abs

Output

It will produce the following output.

50.56
69.04

ceil Method in Ruby

The ceil method is used when we want to return a smallest integer that is greater than or equal to that integer.

Example

Consider the code shown below.

puts (5.1).ceil
puts (5.0).ceil
puts (-5.1).ceil

Output

It will produce the following output.

6
5
-5

eql? Method in Ruby

The eql? method is used when we want to check if the object we pass to a float contains the same value or not.

Example

Consider the code shown below.

puts 5.2.eql?(2)
puts 2.2.eql?(2.2)

Output

It will produce the following output.

false
true
raja
Updated on 12-Apr-2022 08:26:02

Advertisements