[Talking-Ruby] The Safe Navigation Operator in Ruby 2.3.0 Release
The Safe Navigation Operator
In Ruby 2.3.0 Release, A safe navigation operator (so-called lonely operator) &., which already exists in C#, Groovy, and Swift, is introduced to ease nil
handling as obj&.foo
. Array#dig
and Hash#dig
are also added.
Safe Navigation Operator (&.) and Object#try method
The most interesting addition to Ruby 2.3.0 is the Safe Navigation Operator(&.
).
1 | # Good |
Undefined method when &., Object#try, Object#try!
1 | account = Account.new(owner: Object.new) |
Pitfalls
1 | nil.nil? |
Array#dig and Hash#dig
Ruby 2.3 brings Array#dig
and Hash#dig
lets you easily traverse nested hashes, arrays, or even a mix of them. It returns nil
if any intermediate value is missing.
1 | x = { |
References
[1] Ruby 2.3.0 Released - https://www.ruby-lang.org/en/news/2015/12/25/ruby-2-3-0-released/