OneBite.Dev - Coding blog in a bite size

convert variable from string to int in Ruby

Code snippet on how to convert variable from string to int in Ruby

  x = "42"
  x = x.to_i

This code converts the variable x from a string to an integer (whole number). The first line assigns the string value “42” to the variable “x”. The second line then converts the variable x from a string to an integer. The .to_i method is a built-in method in Ruby that changes the variable type from a string to an integer. The conversion is then stored in the same variable: x. The result is that the variable x will now have the value of 42, instead of the string “42”.

ruby