This forum is now read-only. Please use our new forums! Go to forums
How to include multiple values on a key? And then iterate?
The lesson has conveyed that keys can have multiple values.
How would multiple values be created, for instance, in this exercise? (e.g. If I wanted to add a description of the movie using a string along with the numerical rating, how would I be able to do that?)
And then once multiple values are assigned to a key, how can you iterate over those values? For instance, how could I puts out just the movie description or just the rating?
For reference, here’s what I would like to be able to write in order to do this. (Granted, I know it doesn’t work at all…)
movie_ratings = {
memento: 3, "ok",
primer: 3.5, "decent",
the_matrix: 3, "ok",
truman_show: 4, "good",
red_dawn: 1.5, "meh",
skyfall: 4, "good",
alex_cross: 2, "not great",
uhf: 1, "awful",
lion_king: 3.5, "decent"
}
movie_ratings.each_value {|value1, value2| puts value2}
Answer 534ef29d80ff33646600384a
The lesson has conveyed that keys can have multiple values.
If the exercise text suggests that anywhere, it’s certainly incorrect. Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once. So {:a => 1, :b => 1}
is a valid Ruby Hash, but {:a => 1, :a => 2}
isn’t (well, you can actually type that latter Hash in, but then the value for the key :a
will be 2
, that is, the first value gets overwritten).
That being said, any kind of object can be the value of a key in a Ruby Hash. So for storing lists of things, you can store Arrays:
holiday_expenses = {
food: [23.99, 4.35, 8.95],
travel: [134.95, 12.45],
accommodation: [413.17]
}
In this fashion you could store the rating as the first member of your Array, the verbal description as the second member:
movie_ratings = {
memento: [3, "ok"],
# ...
}
Then to access them you’d have to say
puts movie_ratings[:memento][1] #=> ok
You can also store Hashes in a Hash:
movies = {
skyfall: {
year: 2012,
oscars: 2,
starring: ["Daniel Craig", "Judi Dench"]
}
}
and then access the single bits of information by name:
movies[:skyfall][:starring].first #=> "Daniel Craig"
Or you can define a custom class to represent a movie, then create instances of that class, and store those instances in a Hash. The possibilities are limitless.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
1 comments
nice answer :)