Ruby 有没有办法阻止用户在访问另一个 function/procedure 之前通过 case 调用 function/procedure?

Ruby is there a way to stop the user from calling a function/procedure through case before they have accessed a different function/procedure?

我有一个文本文件,我想先打开它进行读取或写入,但希望用户首先手动输入 text_file 名称(打开文件进行读取),如下所示:

def read_in_albums
    puts "Enter file name: "
    
    begin
        file_name = gets().chomp
        if (file_name == "albums.txt")
            puts "File is open"
            a_file = File.new("#{file_name}", "r")
            puts a_file.gets
            finished = true
        else 
            puts "Please re-enter file name: "  
        end
    end until finished
end

从下面这个未完成的代码,selecting 1 将转到上面的过程。我希望用户先 select 1,如果他们选择 2 而没有经过 read_in_albums,他们只会收到某种消息,例如“没有文件 selected 并发送回菜单屏幕.

def main()
  finished = false
  begin
    puts("Main Menu:")
    puts("1- Read in Album") 
    puts("2- Display Album Info")
    puts("3- Play Album")
    puts("4- Update Album")
    puts("5- Exit")
    
    choice = read_integer_in_range("Please enter your choice:", 1, 5)
    case choice
    when 1
      read_in_albums
    when 2
      display_album_info  
    when 5
      finished = true
    end
  end until finished
end
    
main()

我唯一能想到的就是

when 2
        if(read_in_albums == true)
            display_album_info  

并从 read_in_albums.

开始 return 为真

我不想这样做,因为它只是再次经历 read_in_albums,而我只希望它在用户按下 1 时这样做。

您可以在选择选项 1 时设置一个标志

has_been_read = false
...
when 1 
    read_in_albums
    has_been_read = true
when 2
    if has_been_read
        display_album_info
    else
        puts "Select Option 1 first"
    end

或者只是测试你的文件名是否是一个有效的字符串。

您的应用程序的所有功能都取决于相册数据是否已被读取。毫无疑问,您将此数据存储为某个变量引用的内存中的对象。

$album_data = File.read 'album.txt'

您可以测试是否存在此数据,以确定文件数据是否已被读取:

if $album_data.nil?
  # ask user for album file
else
  # show album user interface
end

不需要单独的标志。内存中数据的存在本身就是一个标志。