8/8 Trying to add an update method?



So i'm trying to add a method that update file names to test and refresh my mind on past lessons. Everything in my code seems to work fine except for the update method i've written. I'm told that there might be an infinite loop but I can't figure it out. Is it because I can't .each an instant method?

Here's my code:

    def update
        puts "Which file would you like to update?"
        file_to_update = gets.chomp
        @files.each { |filename, time| 
        if filename == file_to_update
            puts "What would you name your new file?"
            new_file = gets.chomp
            time = Time.now
            @files[new_file] = time
            puts "File '#{new_file}' has been updated by #{@username} at #{time}."
            puts "The file does not exist." 

And if any of you have a better idea as to how I might be able to optimize and simplify the code, please do share! Thanks all. :smile:


I don't know much Ruby so can't tell why you got the error but I can tell that the structure of your code:

for each (filename, time) in @files:
    if input matches filename # do update
    else # show error

doesn't seem quite right. This is because, imagine if you had ten files A, B, C..., J. And the user inputs "I". Now, he'll see the message "The file does not exist." for each of the 8 files A, B, ... H.

Your proper code should be:

matched_file = nil # storage

for each (filename, time) in @files:
    if input matches filename:
        matched_file = filename

if matched_file.nil? # input did not match any file
    print "File not found"
    # file found, do file update

You can also break out of the .each block after the line matched_file = filename since once one file has been matched the others following it need not be checked.

Hope it helps! :slight_smile:


@files is a hashmap, looking up a value is a constant-time operation (independent of the number of key-value pairs)

Don't iterate through every single key-value pair. Just look it up.

You'll need to check if it's there first (no, not with a loop)
alternatively handle exceptions for when the key isn't in the hashmap


Hehe, I forgot that altogether :stuck_out_tongue: Well, then my approach is only useful if @files is a 2d array