我正在做一个程序,我想在模块中输出一个带有两个子菜单的菜单。我只想在运行程序时显示主菜单。然后从主菜单中导航到子菜单并返回。如果有人能找到一个更好的方式来做这件事(我很肯定),请说出来。我甚至不确定这会起作用。谢谢!
module Menus
def self.getValidPositiveNumber
input = gets.chomp
while (input.to_i.to_s != input && input.to_f.to_s != input) do
puts "Ogiltig data. Försök igen."
input = gets.chomp
end
# Är talet större än 0?
number = input.to_f
if (number <= 0)
puts "you cant put that."
getValidPositiveNumber
end
return number
end
def self.get_valid_input(valid_options)
input = gets.chomp
while (!valid_options.include?(input) && !valid_options.include?(input.to_i))
# både Range och Array har include?
puts "no good, please choose something inbetween " + valid_options.inspect
input = gets.chomp
end
return input
end
class Menu
attr_reader :valid_options_range, :menu_string
def initialize(valid_options_range, menu_string)
@valid_options_range = valid_options_range
@menu_string = menu_string
end
def do_menu_action(action)
raise "Has to be called to in any subclass!"
end
def to_s
return @menu_string
end
end
MAIN_MENU = <<END
"---------------------------"
Welcome to Ruby Camping!
Menu
1. Checkin
2. Checkout
3. Lists
4. Economy
5. Exit
What do you want to do?
"---------------------------"
END
def make_menu_choice(choice)
case choice
when 1:
$camping.check_in
when 2:
$camping.check_out
when 3:
$current_menu = LISTS_MENU
when 4:
$current_menu = ECONOMY_MENU
when 5:
exit
end
end
LISTS_MENU = <<END
"---------------------------"
-- 1. List current guests --
-- 2. List all guests --
-- --
-- 0. Back to Main menu --
------------------------------"
END
def make_menu_choice(choice)
case choice
when 1:
$camping
when 2:
$camping.all_guests
when 0:
$current_menu = MAIN_MENU
end
end
ECONOMY_MENU = <<END
"---------------------------"
-- 1. List current guests --
-- 2. List all guests --
-- --
-- 0. Back to Main menu --
------------------------------"
END
end
puts Menus::MAIN_MENU
if Menus == 3 then LISTS_MENU = Lists_Menu.new
elsif Menus == 4 then ECONOMY_MENU = Economy_Menu.new
end
__END__
答案 0 :(得分:0)
我不会为你写代码(对不起),但我会这样做:
一个通用菜单类,可以提供映射到数字和方法名称符号的菜单项......
然后我会创建一个包含所有菜单项方法的类,并动态地将菜单类实例化为我需要它并为其提供所需信息...
从菜单中,方法将以
的方式调用ClassHoldingMethods.method( methodname[entered_number] ).call
(在这种情况下,methodname是一个数组映射索引到选择时要调用的方法,并且输入了来自用户的已经检查过的数字的编号)
那会更干净,因为菜单类会很灵活,你可以轻松添加新的菜单页......
答案 1 :(得分:0)
您应该考虑使用commander gem,其中包含highline gem,这两者都旨在方便用户输入和验证。