Ragunandhan.B
Ragunandhan.B

Reputation: 82

Throwing Error in Rescue method?

I'm New to ruby,learning basics,I want to enter only Integer Values in age field,Need to Throw Not a number when it is a string when executing the following code

puts "Enter Age "

age=Integer(gets) rescue nil

if age.is_a?(Numeric)

puts "Your age is #{age}"

else 

puts "Not a Number"

end

if age>25 

puts "You are Permitted"

else 

puts "Not allowed"

end

getting error as ': undefined method `>' for nil:NilClass (NoMethodError) What am doing wrong ?

Upvotes: 0

Views: 65

Answers (3)

Adrian
Adrian

Reputation: 425

You don't need to rescue to nil because you're planning to get and respond to whatever the user inputs and you don't need to raise because you don't want the program to exit after the user inputs a non Integer.

This is probably what you need:

age = ""
loop do
    puts "Enter Age "
    age = gets.chomp
if age.to_i.to_s == age.to_s
    puts "Your age is #{age}"
else 
    puts "Not a Number"
    next
end

if age.to_i > 25 
    puts "You are Permitted"
    break
else 
    puts "Not allowed"
    break
end
end until age.to_i.to_s == age.to_s  

next will make it go back and do the next loop, and break will break out of the loop. You can use age.to_i.to_s == age.to_s to really check if age is an integer.

Upvotes: 1

David Grayson
David Grayson

Reputation: 87386

You wrote puts "Not a number" which will print a message but then your program will keep running as usual. On that line, try replacing "puts" with "raise" and then read about Ruby exceptions.

Upvotes: 2

sawa
sawa

Reputation: 168081

The user input was not in a format to give an integer, so by rescue, age became nil. You tried to apply > on it in if age>25, which is not defined.

Upvotes: 3

Related Questions