首页 > 解决方案 > Ruby:(如果可能)如何在程序执行以构建菜单方法时在 while 循环中构建 case 语句?

问题描述

有史以来第一个问题,

我最近发现了 TTY,特别是 TTY-prompt,我想知道是否有一种方法可以让我的程序在运行时构建 Ruby 代码,目标是即时制作 tty-prompt 菜单并保持 DRY尽可能。

到目前为止,我有一个提示选择方法:

def menu_selection(menu_name, menu_options)
    return $prompt.select(menu_name, menu_options)
end

这得到了这些预定义的值:

main_menu_name = "Main menu:"
main_menu_options = ["Option 1", "Option 2", "Option 3", "Option 4", "Exit"]

进入这个预定义的菜单:

selection = ""
while selection != "Exit"
    system "clear"
    selection = menu_selection(main_menu_name, main_menu_options)
    case selection
    when "Option 1"
        # code
    when "Option 2"
        # code
    when "Option 3"
        # code
    when "Option 4"
        # code
    end
end

在我的代码中,我上面有大约 6 个这些预定义菜单,有没有办法根据 main_menu_options array.length 和输入 when 使用变量的元素生成何时需要这些菜单?

基本上是这样的:

def menu_builder
    # *Edits below*
    # Builds selection variable with empty string
    # Builds while loop with condition
    # Builds Case Statement
    # n = 1
    # while n < main_menu_options.length do |index|
    #    Build when_n with index_n
    #    n += 1
end

# Method above builds menu code below (Doesn't have to be a method if something else works
selection = ""
while selection != "Exit"
    system "clear"
    selection = menu_selection(main_menu_name, main_menu_options)
    case selection
    when_1 option_1
        # code
    when_2 option_2
        # code
    (...) # Continues to build when's and variables
        # code
    when_n option_n
        # code
    end
end

任何反馈/批评表示赞赏,如果我发布了不正确的内容,请告诉我,干杯。

标签: ruby

解决方案


正如@Sergio Tulentsev 上面提到的,您无法在 上完成此操作ruby (until now 2.7),但是您可以使用另一种方法来解决此问题,我认为最适合您的问题的是创建一个hash of functions,例如:

menu_options = {}
menu_options[:option_1] = method(:code_for_option1) #storage the function called code_for_option1 inside the hash
menu_options[:option_1].()

然后,如果您需要一个新选项,您只需将其添加到带有关联函数的哈希中。此外,您可能会在哈希中发现此答案有用的存储功能 希望以上有所帮助!


推荐阅读