Lesson 6 of 10
Hashes and symbols
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Symbols and default values
Explanation
A Hash is Ruby's dictionary: it maps each key to a value, like user = { name: "Layan", city: "Riyadh" }. The keys here are symbols (Symbol), and name: is shorthand for :name =>. A symbol is a fixed name, and every :name in a program is the very same object, which is why Ruby usually uses symbols as keys. But a symbol isn't equal to a string, so user["name"] returns nil, because the key is :name.
If you ask for a key that doesn't exist, you won't get an error: user[:plan] quietly returns nil. fetch(:plan, :basic), on the other hand, returns the value if the key exists and the default if it doesn't, and key?(:plan) asks explicitly whether the key is there. Watch out for user[:newsletter] || true: if the stored value is false, || replaces it with true and overrides the user's choice, while fetch tells a missing key apart from a key whose value is false.
You loop over the key and value pairs with each { |key, value| ... }. Note that map on a hash returns an array, not a hash, while transform_values returns a new hash with the same keys and changed values.
Your task
From user, get plan with fetch and a default of :basic, get newsletter with fetch and a default of true, and work out has_email with key?. Then, from the monthly prices in prices, work out the hash yearly with transform_values, where a year costs the same as ten months. After that, build lines from yearly with map in the form "basic: 290", and print each line with each.
Checks
6 checks- plan is :basic because the key doesn't exist
- newsletter stays false because the key exists
- has_email is false because there's no :email key
- yearly holds the price of ten months for every plan
- Each item in lines looks like "basic: 290"
- Every plan was printed on its own line