Ruby String To Integer Conversion Tutorial

In this section, we will learn how to convert a string value into an integer value.

How to Convert a String value to Integer in Ruby?

When you have a string value in your program that contains a number and you want to convert that string into an integer, we can use the to_i method.

Note that this method works only if the target string value starts with numbers! But it doesn’t matter if it also contains other types of characters too as long as its beginning characters are of type integer.

This method also works with floating values as well and basically will drop the decimal part of the value and return the whole part instead.

Also remember that if you have a user made object, you can also override this method on that object and set an integer value to be returned whenever you’ve called the method.

Ruby to_i Method Syntax:

The method does not take an argument. Simply call this method on a floating or a string value and you’ll get the integer representation of that value.

Example: using to_i method in Ruby

puts (332.44).to_i

puts "324fst".to_i

Output:

332

324
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies