Integer / to_i not working properly


#1



Control Flow in Ruby: 1. How it works


undefined method `to_i!' for "variable":String

I listed the four different ways I am trying this line of code, and I can't figure out why one of them won't work. Any ideas?


print "Integer please: "
user_num2 = gets.chomp
user_num2.to_i!
# returns an error

user_num = Integer(gets.chomp)
# works fine

user_num1 = gets.chomp.to_i
# works fine

user_num3 = gets.chomp
user_num4 = user_num3.to_i
# works fine


#2

@bingemonkey,
If you use the so-called bang operator !
to called Method will try to change the object on which its called itself...

You cannot do this with a string as it is un-mutable_

Read some == discussions / opinions ==

http://stackoverflow.com/questions/612189/why-are-exclamation-marks-used-in-ruby-methods
http://stackoverflow.com/questions/36051403/ruby-conversion-from-string-to-int
http://stackoverflow.com/questions/38517297/ruby-to-i-method-not-working-wondering-why


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.