nil safety in Ruby
The operators that keep nil from taking down a call chain.
config = { "theme" => "dark" }
# &. calls the method only when the receiver is not nil
user = nil
puts user&.length.inspect
# ||= assigns only when the current value is nil or false
cache = nil
cache ||= "computed once"
puts cache
# fetch raises on a typo; a default makes the fallback explicit
puts config.fetch("theme")
puts config.fetch("font", "mono")
puts config["missing"].to_s.empty?
How it works
&.returns nil instead of raising when the receiver is nil.||=assigns only when the current value is nil or false.fetchraises on typos unless you hand it an explicit default.
Keywords and builtins used here
puts
The run, in numbers
- Lines
- 15
- Characters to type
- 393
- Tokens
- 69
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 52 seconds.
Step 1 of 3 in Nil & idioms, step 22 of 29 in Language basics.