A
Adam Bourg
I wrote a basic script that asks for your age then converts it into
months, days and weeks old. I wanted to add some sort of control so that
it would return an error if you didn't enter a number but rather a word
or a letter or something.
Can you please give me pointers? I've done quite a bit of Googling and
am not sure how to do this. When I enter a number or a letter it
returns the else statement. Please help! See attached for example of it
being run.
Here's my script below:
# Basic Program to ask for a persons age and out put that in months
# Writen by Adam Bourg on 2010-07-11
# Define verables
months = 12
# Question that asks for your age
puts "Hello, in the field below please enter your age:"
# Get's is the ruby method that asks for your age, it gets the
information from # the terminal when you type
age = gets
# This checks to see if you input a number, if you do it outputs the
results
# if you don't it asks you for it in a numerical format eg 21
if ( age.to_f.to_s == true )
monthsold = age.to_i * months.to_i
puts 'You are ' + monthsold.to_s + ' months old'
else
puts 'Error, please enter a number!'
end
Attachments:
http://www.ruby-forum.com/attachment/4848/Screen_shot_2010-07-11_at_10.33.56_AM.png
months, days and weeks old. I wanted to add some sort of control so that
it would return an error if you didn't enter a number but rather a word
or a letter or something.
Can you please give me pointers? I've done quite a bit of Googling and
am not sure how to do this. When I enter a number or a letter it
returns the else statement. Please help! See attached for example of it
being run.
Here's my script below:
# Basic Program to ask for a persons age and out put that in months
# Writen by Adam Bourg on 2010-07-11
# Define verables
months = 12
# Question that asks for your age
puts "Hello, in the field below please enter your age:"
# Get's is the ruby method that asks for your age, it gets the
information from # the terminal when you type
age = gets
# This checks to see if you input a number, if you do it outputs the
results
# if you don't it asks you for it in a numerical format eg 21
if ( age.to_f.to_s == true )
monthsold = age.to_i * months.to_i
puts 'You are ' + monthsold.to_s + ' months old'
else
puts 'Error, please enter a number!'
end
Attachments:
http://www.ruby-forum.com/attachment/4848/Screen_shot_2010-07-11_at_10.33.56_AM.png