Search code examples
rubyhashterminalsymbols

Just started learning Ruby; Why does my code work properly in the Codeacademy environment but not in the Mac Terminal?


Completed a mini project on Hashes & Symbols, and wanted to see how it ran in the terminal.

It executes perfectly in Codeacademy, but in the terminal it's printing out the wrong responses, seemingly because it's not correctly referencing the hash array.

Despite the input I give the terminal not existing in the hash array, it prints "It's already on the list!"

Is codeacademy teaching me incorrectly, or is there some terminal-specific issue with my code?

movies = {
  Hackers: 8.0,
  Gladiator: 9.0,
}

puts "Would you like to add, update, display, or delete movies?"
choice = gets.chomp

case choice
when "add"
  puts "What's the movie called?"
  title = gets.chomp.to_sym
  puts "What would you rate it out of 10?"
  rating = gets.chomp.to_i
    if movies[title.to_sym] = nil
    movies[title.to_sym] = rating.to_i
    puts "The movie has been added!"
    else puts "It's already on the list!"
    end

Solution

  • = is a assignment operator and == is a comparison operator. = operator is used to assign value to a variable and == operator is used to compare two variable or constants. It is important to know the difference, the Code Academy environment is maybe accounting for the issue. Ruby also has a === operator.

      movies = {
      Hackers: 8.0,
      Gladiator: 9.0,
    }
    
    puts "Would you like to add, update, display, or delete movies?"
    choice = gets.chomp
    
    case choice
    when "add"
      puts "What's the movie called?"
      title = gets.chomp.to_sym
      puts "What would you rate it out of 10?"
      rating = gets.chomp.to_i
        if movies[title.to_sym] == nil
          movies[title.to_sym] = rating.to_i
          puts "The movie has been added!"
        else 
          puts "It's already on the list!"
        end