Forum: Ruby Trapping errors, a simple example

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
508861510639b56d61eb30e6a28b01d9?d=identicon&s=25 John Maclean (Guest)
on 2006-01-05 17:44
(Received via mailing list)
Hey Chaps,

Here's a really simple menu with only 4 options. I'd like to be able do
some simple error trapping... How's it done?

#!/usr/bin/ruby
#Wed Jan  4 06:17:22 GMT 2006
class TopMenu
  def welcome
    puts "Welcome to de-blah-de-blah-de-blah"
    puts "~~~~~~~ ~~ ~~ ~~~~ ~~ ~~~~ ~~ ~~~~~"
  end

  def options
    # we will use this data to create a class called Option
    # each option will have a new menu
    # and will be a child class of the main one
    print "------------------------------------\nmenu - Which stage are
you at?\n------------------------------------\n0:- Before site work\n1:-
During site work\n2:- After site work\n3:- Other stuff\nq:- quit!\n"
  end

  # grab the input
  def topchoice
    print "enter your choice (0,1,2,q) : "
    p =  $stdin.gets # TODO:- check it's validity # TODO:- is the choice
a number in the correct range?  # TODO:- does he wanna quit?
    print "you have chosen #{p}"
    if p == "0"
      print "you have chosen #{p}"
    else
      if p == "q"
      print "you have chosen #{p}"
    end
  end
end




# create a new instance
top = TopMenu.new
top.welcome
top.options
top.topchoice
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-01-05 17:47
(Received via mailing list)
John Maclean wrote:
>     puts "~~~~~~~ ~~ ~~ ~~~~ ~~ ~~~~ ~~ ~~~~~"
>
>   # grab the input
>   def topchoice
>     print "enter your choice (0,1,2,q) : "
>     p =  $stdin.gets # TODO:- check it's validity # TODO:- is the

p.chomp!

if /\a[012q]\Z/
  # ok
  case p
    when 0
    when 1
....
  end
else
  # error
end

HTH

    robert
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-01-05 19:57
(Received via mailing list)
On Jan 5, 2006, at 10:37 AM, Robert Klemme wrote:

>>     puts "Welcome to de-blah-de-blah-de-blah"
>> quit!\n" end
>   case p
>     when 0
>     when 1
> ....
>   end
> else
>   # error
> end

You might also want to take a look at HighLine[1], which can make
this kind of user interaction easier.

1:  http://rubyforge.org/projects/highline/

James Edward Gray II
This topic is locked and can not be replied to.