Safe navigation and fetch in Ruby

Ruby

&. stops at nil; fetch raises rather than returning nil when a key is genuinely required.

city = user&.address&.city || 'unknown'

port = config.fetch('port')          # raises if absent
host = config.fetch('host', 'localhost')

More in Ruby

Random picks