How to convert string object into integer?

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

Hi all, I’m new to ruby.
Here is the example code I was trying to test.
But it popped up an error message that like “failed to compare string object to 0”.
So how to convert a string to an integer?
Thanks a lot!
<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

``` print "input a integer" x = gets.chomp if x > 0 print "Positive" elsif x < 0 print "Negative" else print "zero" end ```

To convert a string to an integer, use,

x.to_i

It is not an in-place mutation, though, so it needs to be assigned or passed as an argument in a method call expression.

y = x.to_i

or

y = my_method(x.to_i)

Thanks a lot, but I don’t understand what is “in-place” mutation yet. :neutral_face:

1 Like

An in-place mutation (insitu) is when the change (mutation) is written back onto itself.

s = "some string"
t = s.capitalize
puts t           # Some string
puts s           # some string
s.capitalize!    # notice the !
puts s           # Some string
1 Like