Useful Methods of Integer Class in Ruby

RubyServer Side ProgrammingProgramming

Ruby's integer class is the foundation for the two concrete classes that represent whole numbers. Bignum and Fixnum are these concrete classes. Bignum holds the integer value that is outside the range of Fixnum, which is displayed in the native machine word.

There are a variety of methods in the integer class that can be used to perform various tasks. Numeric class has a subclass called Integer. Let's check some of the useful methods that are available in the integer class in Ruby.

to_i method

The to_i method is used to return an integer. Consider the code shown below

Example

Consider the code shown below.

num = "10"
puts num.to_i

Output

It will produce the following output.

10

chr method

The chr method is used to return a string. Consider the code shown below.

Example

Consider the code shown below.

puts 69.chr
puts ?b.chr

Output

It will produce the following output.

E
b

floor method

The floor method takes an integer and returns the largest integer which is smaller or equal to the input integer. Consider the code shown below.

Example

Consider the code shown below.

puts 69.floor
puts (-13).floor

Output

On execution, it will produce the following output

69
-13

integer? method

The integer? method is used when we want to check whether a variable is an integer or not, as it returns True for integer values and False for non-integer values. Consider the code shown below.

Example

Consider the code shown below.

puts 69.integer?
puts (1.3).integer?

Output

It will produce the following output.

true
false

next method

The next method is used when we want to return the successive integer of the current integer. Consider the code shown below.

Example

Consider the code shown below.

puts 69.next
puts (-3).next

Output

It will produce the following output.

70
-2
raja
Updated on 12-Apr-2022 08:54:48

Advertisements