Ulrich Holtzhausen wrote:
Hi,
I'm all new to programming and all new to Ruby - hope I haven't made a
mistake by choosing this language.
I'm trying to teach myself by creating tiny (mostly useless) little
applications and then extend on them as I learn.
Today I started out and this is what I got:
#!/usr/bin/env ruby
#Favourite number
puts "What is your favourite number?"
num = gets.to_i
if num != Integer
puts "Please type a number"
else
better = num + 1
puts "Hah! #{num} is pathetic! #{better} is a much better number!!!"
end
Somewhere along the line there's a mistake however, but I take it you
guru's can see what I'm trying to do here?
How can I check if the variable 'num' is an integer and if not, ask the
user to re-input with an integer?
Thanks in advance!
The mistake is that Integer is a class in Ruby, so your test "num != Integer" is testing to see if num is not equal to the Integer class. It never will be equal, of course.
The gets method always returns a string. You are calling .to_i on the string to convert it to an integer, which will work the way you expect as long as the string is sequence of digits (with an optional leading sign, of course.) However, .to_i happily "converts" non-integer strings as well. Bring up irb and try it yourself:
irb(main):001:0> "20lbs. of fertilizer".to_i
=> 20
irb(main):002:0> "x".to_i
=> 0
Oops! It ignored the non-digit characters after "20" and converted "x" to 0. Not what you wanted to happen, but it's working as documented:
~$ ri String.to_i
------------------------------------------------------------ String#to_i
str.to_i(base=10) => integer
···
------------------------------------------------------------------------
Returns the result of interpreting leading characters in str as an
integer base base (2, 8, 10, or 16). Extraneous characters past
the end of a valid number are ignored. If there is not a valid
number at the start of str, 0 is returned. This method never
raises an exception.
What you want is the Integer() method, which will raise an exception when given an invalid argument. Then you catch the exception.
begin
n = Integer(str)
rescue ArgumentError
puts "Not an integer!"
end
Good luck!
--
RMagick: http://rmagick.rubyforge.org/