As I understand it, the way to accept user input is
puts "Can you guess what number the computer is thinking of?"
userguess = gets.chomp
gets.chomp
is a string method and so if the user enters the number 5
, userguess
stores the value "5"
as string. I would then have to do userguess.to_i!
to convert this to an int. However, I would not like to do this. I want to accept the user input either as a string or an int and then have the program do something like:
if @guess.is_a?(Integer) == true
puts "I got your number. Let me get back to you."
# do something
elsif @guess.is_a?(Integer) == false
puts "That's not a number. You MUST enter a number! Try again"
# Ask the user to guess again.
else
#something else
end
I don't want to accept the user input explicitly as a string because I want to check if it is a string or an int later on in the program. How would I do this?
gets.chomp
is wrong in the first place. The way to accept isgets
. And there is no such thing asto_i!
. Changing the receiver's class while retaining its id is impossible. – sawas = gets.chomp; if s[/^-?\d+$/] ....
– Cary Swoveland 7 mins ago edit – Cary Swoveland