How to Use the Ruby to_i Method

09/22/2021

Contents

In this article, you will learn how to use the Ruby to_i method.

Using the to_i method

The to_i method is a built-in method in Ruby that converts a given object to an integer. This method is commonly used when you need to convert a string or floating-point number to an integer.

Here’s the basic syntax of the to_i method:

object.to_i

Where object is the object that you want to convert to an integer. The to_i method returns an integer object that represents the converted value.

Using the to_i method with strings

One of the most common use cases for the to_i method is to convert a string to an integer. When you call the to_i method on a string, Ruby tries to convert the string to an integer. If the string contains non-numeric characters, the to_i method will return 0. Here are a few examples:

"42".to_i   # returns 42
"3.14".to_i # returns 3
"foo".to_i  # returns 0

Using the to_i method with floating-point numbers

You can also use the to_i method to convert floating-point numbers to integers. When you call the to_i method on a float, Ruby simply drops the decimal part and returns the integer part. Here’s an example:

3.14.to_i # returns 3

Using the to_i method with other objects

You can also call the to_i method on other objects, but the result might not always be what you expect. Here are a few examples:

true.to_i  # returns 1
false.to_i # returns 0
nil.to_i   # returns 0

As you can see, calling to_i on a boolean or nil object will always return either 0 or 1.