8/8 Trying to add an update method?


#1

https://www.codecademy.com/courses/ruby-beginner-en-X5wcR/0/6?curriculum_id=5059f8619189a5000201fbcb

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}."
        else 
            puts "The file does not exist." 
        end 
        }
    end


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:


#2

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"
else
    # 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:


#3

@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


#4

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