How to convert string object into integer?

ruby

#1



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!


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


#2

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)

#3

Thanks a lot, but I don't understand what is "in-place" mutation yet. :neutral_face:


#4

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