Forum: Ruby (help a beginner) Loop bug

22e5646b6066ed88b57700026bc9722b?d=identicon&s=25 Pierre Turnbull (nounoursnoir)
on 2017-01-21 17:07
Attachment: aaruby.png (40 KB)
hello world!
i'm a beginner at Ruby language, and i'm facing a problem for which i
fail to find the solution.

I will put a big block of code since I don't know where the error comes
from...
The problem is that when I answer something else than "yes" or "no" to
the question "Finished?", the program stops the while loop and goes to
the next block of code. Instead of stopping it, it should ask me again
to put "yes" or "no", until I put "yes" or "no".

I also join a screenshot of my code so you can see it better. (note: in
this post, i've deleted some useless part of code and traducted some
comments from french to english)

Here is my code:


list = Array.new
finished = "no"
#create a hash in which the values are lists of values, so i can have
keywords corresponding to authors, and lists of values corresponding to
the lists of files created by each author
hash = Hash.new do |hsh, key|
    hsh[key] = []
end

while finished == "no"
    puts "What file would you like to implement?"
    file = gets.chomp
    time = Time.now
    puts "Who's the author?"
    author = gets.chomp

    if hash[author].include? file
        puts "There already is a file named \"#{file}\" corresponding to
the author \"#{author}\"."
    #gives a value to the value-list of a key
    else hash[author].push(file)
    end

    puts "\nFinished? yes/no"
    finished = gets.chomp
    finished.downcase!
    puts ""

    #here, whenever i give the variable finished another value than
"yes" or "no", it should ask again the user to put a value in the
variable finished, until the value given is "yes" or "no"
    case finished
    when finished == ""
        finished = gets.chomp
        finished.downcase!
    when finished != "yes" && finished != "no" && finished != ""
        puts "Put \"yes\" or \"no\" please!"
        finished = gets.chomp
        finished.downcase!
    end

end
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2017-01-23 14:24
Your case statement doesn't make sense. You compare a String (finished)
to the result of a logical expression, i.e. true or false. Basically,
your case block is equivalent to

    if finished === (finished == "")
      ....
    elsif finished === (finished != "yes" && finished != "no" &&
finished != "")
      ...
    end
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.