How to Convert String to Number in Ruby

09/22/2021
Contents
In this article, you will learn how to convert string to number in Ruby.
Converting string to number
In Ruby, you can convert a string to a number using several built-in methods. Here are some examples:
to_i method
Converts a string to an integer.
string_num = "123"
int_num = string_num.to_i
puts int_num # Output: 123
to_f method
Converts a string to a floating-point number.
string_num = "3.14"
float_num = string_num.to_f
puts float_num # Output: 3.14
to_r method
Converts a string to a rational number.
string_num = "2/3"
rational_num = string_num.to_r
puts rational_num # Output: (2/3)
to_c method
Converts a string to a complex number.
string_num = "3+4i"
complex_num = string_num.to_c
puts complex_num # Output: (3+4i)
Note that if the string contains non-numeric characters, the conversion may not succeed and the result will be 0 or nil, depending on the method used. Therefore, it’s important to ensure that the string contains only numeric characters before attempting to convert it to a number.