There are two forms of case block and you have sort of mixed them up.
Either of the following defs of double_it will work. I think the
first, using a case without a target, is probably what you want, but
the second, a case with a target (compares target to pattern with
===), can be made to work, too.
Hope this helps.
def double_it
print "Please enter a whole number (or type 'h' for help) : "
num = gets.chomp
case
when num == 'h'
puts "A whole number is 45 for example, or 12564."
double_it
when (n = num.to_i) > 1
puts n * 2 # doubling not squaring
else
puts "Input must be positive number!"
double_it
end
end
double_it
print "Press any key to exit: "
STDIN.getc
def double_it
print "Please enter a whole number (or type 'h' for help) : "
num = gets.chomp
case num
when 'h'
puts "A whole number is 45 for example, or 12564."
double_it
when /^[^-]\d+/
puts num.to_i * 2 # doubling not squaring
else
puts "Input must be positive number!"
double_it
end
end
double_it
print "Press any key to exit: "
STDIN.getc
Regards, Morton
On Jul 19, 2006, at 5:05 AM, simonh wrote:
> decided to have a go at using the case statement. Why won't this work?
>
> ----------------------------------------------------------------------
> ---------------
> def double_it
> print "Please enter a whole number (or type 'h' for help) : "
> num = gets.chomp
> case num
> when num == 'h'
> puts
> puts "A whole number is 45 for example, or 12564."
> puts
> when num.to_i > 1
> num * num
> print num.to_s
> when num.to_i <= 0
> puts "The number must be positive!"
> end
> end
> double_it
> gets
> ----------------------------------------------------------------------
> ----------------
>
>