Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Hash get value, get default value

  • Get value of a key
  • Get value or nil if the key does not exist
  • Get value of a default value if the key does not exist
person = {
  "name"   => "Jane",
  "number" => 42,
}
puts person

# Unhandled exception: Missing hash key: "email" (KeyError)
# email = person["email"]
email = person["email"]?
puts email.nil? # true

name = person["name"]?
puts name # Jane

email = person["email"]? || "default@example.com"
puts email.nil? # false
puts email      # default@example.com