Home > Software engineering >  Ruby is there a way to stop the user from calling a function/procedure through case before they have
Ruby is there a way to stop the user from calling a function/procedure through case before they have

Time:10-20

I have a text file that I want to open first for reading or writing, but want the user to manually enter the text_file name (which opens the file for reading) first like so:

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

From this unfinished code below, selecting 1 would go to the above procedure. I want the user to select 1 first, and if they choose 2 without having gone through read_in_albums they just get some sort of message like "no file selected and sent back to menu screen.

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()

The only thing I can think of is something like

when 2
        if(read_in_albums == true)
            display_album_info  

and have it return true from read_in_albums.

which I don't want to do as it just goes through read_in_albums again, when I only want it to do that if the user pressed 1.

CodePudding user response:

You could either set a flag when option 1 was selcted

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

Or just test if your file name is a valid string.

CodePudding user response:

All of your application's functionality depends on whether the album data has been read. You are no doubt storing this data as an object in memory referenced by some variable.

$album_data = File.read 'album.txt'

You can test whether this data is present in order to determine whether the file data has been read:

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

There is no need for a separate flag. The mere presence of the data in memory serves as a flag already.

  • Related