Does this give you any ideas?
class Menu
def initialize(title, options={})
@title,@options = title,options
@selected = nil
end
def display
@options.each do |key,val|
puts '#{key} - #{val}'
end
print '\n>'
end
def choose(item)
if @options[item]
@selected = item
else
raise 'Invalid choice'
end
end
def invoke
if @selected
@options[@selected].execute
else
raise 'No choice'
end
end
end
class Command
def initialize(name)
@name = name
end
def to_s
@name
end
def execute
puts 'Command '' + @name + '' executed'
end
end
menu = Menu.new('My Menu',
{ 1 => Command.new('Foo'),
2 => Command.new('Bar'),
3 => Command.new('Baz')})
while true
begin
menu.display
c = $stdin.gets
menu.choose(c.to_i)
menu.invoke
rescue
puts $!.message
end
end
(Comment added by Tyche on Tue Sep 27 11:26:33 2005)By way of translation help....
@variables are instance variables
initialize is a constructor
@options = {} creates an associative array, hash, or map
(Comment added by Tyche on Tue Sep 27 11:55:20 2005)Whoops! Here's what it looks like executing.
$ ruby menu.rb
1 - Foo
2 - Bar
3 - Baz
>1
Command 'Foo' executed
1 - Foo
2 - Bar
3 - Baz
>2
Command 'Bar' executed
1 - Foo
2 - Bar
3 - Baz
>5
Invalid choice
1 - Foo
2 - Bar
3 - Baz
>