1 Replies - 500 Views - Last Post: 10 May 2013 - 02:23 PM Rate Topic: -----

#1 tessierny  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 12-February 13

unexpected boolean result using .nil? on a hash

Posted 10 May 2013 - 02:11 PM

Hi all,
I am working through exercises on codecademy and I came across a solution that I do not completely understand involving .nil? Here is my code :

movies = { GIS: 10.0, Phantasm: 1.5, Bourne: 4.0}
puts "Whats your movie brah?"
title = gets.chomp
puts "What's your rating brah?"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "Your info was saved brah!"
case movies
when 'add'
  puts "What movie do you want to add son?"
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "What's your new rating brah?"
    rating = gets.chomp
    movies[title.to_sym] = rating.to_i
    puts "#{title} has been added with a rating of #{rating}."
  else
    puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
  end
when "update"
 if movies[title.to_sym].nil?
 
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else puts "Error!"
end 


I am only referring to the add method. The rest of the script is a work in progress. I don't like not understanding things though and this has me in a bit of a quandry. My question is does Ruby know not to add a title that already exists because two symbols cannot have the same name? I am curious how it determines when the hash has no value. Can anyone clarify this for me? I would really appreciate it!

Is This A Good Question/Topic? 0
  • +

Replies To: unexpected boolean result using .nil? on a hash

#2 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon



Reputation: 1335
  • View blog
  • Posts: 3,398
  • Joined: 28-November 09

Re: unexpected boolean result using .nil? on a hash

Posted 10 May 2013 - 02:23 PM

You'd be better off to make a movie object to encapsulate a lot of that instead of trying Hash hackery. The second thing is there's a nice short-circuit method that you can use to do almost exactly that: ||=

a = 1
a ||= 5
puts a # => 1


a ||= 5
puts a # => 5


Read and meditate on OOP, Classes, and attr_accessors. This is a good opportunity to take a deeper dive into it.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1