Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Alphonse Cuccurullo
Alphonse Cuccurullo
2,513 Points

Hi can someone help me with a small part of this syntax?

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

Im having trouble understanding the roll of the movies[title.to_sym].nil? part. Like what is that doing is it converting whatever i type into a symbol?

1 Answer

De Ming Liu
De Ming Liu
21,774 Points

Hi, The movies hash:

movies = {
  Memento: 3,
  Primer: 4,
  Ishtar: 1
}

stores the movies as symbols (thus the colon at the end, alternative and original syntax is :Memento => 3 if that makes more sense).

movies[title.to_sym].nil?

The title variable is a "gets" variable, so it stores what you type in, but it stores it as TEXT. .to_sym converts it to a symbol. For examples, if you enter "Memento" from the "gets" command, it stores it as a string. .to_sym then converts it to a symbol. Think of it as:

"Memento".to_sym === :Memento

the:

.nil

part checks if it's empty. If you typed in "Memento" that would be false (because the symbol Memento has a value of 3), but if you for example typed in "Godzilla", it would be true be the symbol :Godzilla is not present and has no number assigned to the symbol.

Hope that helps. If not, message me on Skype and I'll try to explain it better. My Skype is: luckysevensevenseven.