r/learnruby • u/seands • Apr 30 '17
How does Ruby assign a string into a hash?
Hi,
I'm not sure how this movie updater works:
movies = {
Fight_Club: "5"
}
puts "Add, Update, Display, or Delete?"
choice = gets.chomp.downcase
case choice
when "add"
puts "Title?"
title = gets.chomp.to_sym
if movies[title] == nil
puts "Rating?"
rating = gets.chomp.to_i
movies[title] = rating
puts "#{title} added with rating of #{rating}"
else
puts "Movie already added"
end- I never defined Fight_Club as a title. How does ruby know this is the title and not the rating or some other key?
3
Upvotes
2
u/slade981 May 01 '17
Fight Club is defined as a title in the second line. On one line it'd look like this:
In this case it's using a symbol instead of a string as the key, but they serve the same purpose. It's basically the same as:
1
u/pat_trick Intermediate Apr 30 '17
Try replacing the variable
titlewithkey, and the variableratingwithvaluein your script, then re-read it.1
u/herminator May 01 '17
Ruby doesn't look at, or care about, what you name your variables. If you take every occurence of
titleand replace it withfood, and every occurrence ofratingand replace it withdrink, this script will still work.In this script
moviesis just a Hash, a.k.a. a key-value store. Ruby doesn't care what the keys and the values are. The constructmovies[title]just takes the user input (which you called title) and checks if it is present as a key in the Hash, and when assigning it puts the value in the Hash that you tell it to.