Lesson 6 of 10

Hashes and symbols

Goal

Symbols and default values

01

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.

02

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
  1. plan is :basic because the key doesn't exist
  2. newsletter stays false because the key exists
  3. has_email is false because there's no :email key
  4. yearly holds the price of ten months for every plan
  5. Each item in lines looks like "basic: 290"
  6. Every plan was printed on its own line
main.rb
OutputRuby 3.4 (ruby.wasm)

Loading Ruby (about 8 MB). This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.