2 Replies - 531 Views - Last Post: 10 May 2013 - 05:52 PM Rate Topic: -----

#1 tessierny  Icon User is offline

  • New D.I.C Head

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

.nil? value query

Posted 10 May 2013 - 11:54 AM

Hello all,
I am working through the codecademy exercises and I cannot figure out what .nil? means in the way that I am required to implement it. 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] = rating
puts "Your info was totally saved brah!"
case movies
when 'add'
  puts "What movie do you want to add?"
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "What's the rating? (Type a number 0 to 4.)"
    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"
puts "Updated!"
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else puts "Error!"
end


I am working though creating methods for each command starting with the "add" command. The thing that is totally confusing me though, is the
.nil?
. From what I understand,
nil = false
. So, what I am thinking is that
.nil?
is asking if the attached statement is false. The crux of my confusion based on the line :

if movies[title.to_sym].nil?


Is that line asking :

"If the title I just entered is already represented as a symbol in the movies array, is this statement then, false?"

In which case, I imagine the if statement would evaluate to true if the title does not exist and false if it already exists. If the movie is indeed new, it would lastly, simply ask for the pertinent info as stated in the
else
statement.

If someone could help clarify my misunderstanding I would be very grateful!

Is This A Good Question/Topic? 0
  • +

Replies To: .nil? value query

#2 tessierny  Icon User is offline

  • New D.I.C Head

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

Re: .nil? value query

Posted 10 May 2013 - 12:34 PM

I figured it out. Thanks you guys anyway!!
Was This Post Helpful? 0
  • +
  • -

#3 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,140
  • Joined: 14-September 07

Re: .nil? value query

Posted 10 May 2013 - 05:52 PM

For anyone searching this later:

everything in Ruby is an object, nil is a singleton instance of NilClass. So when you call .nil? on an object it checks to see if said object actually exists and is not nil.

If the hash entry does not exist in movies, then gather some information to fill it in, otherwise inform the user that it's already in there.

Good article on it.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1