[Talking-Ruby] Syntactic sugar in Ruby

Syntactic sugar in Ruby

Ruby uses syntactic sugar to make some of its syntax more expressive, or easier to read.

Safe Navigation

Safe Navigation Operator (&.)

The most interesting addition to Ruby 2.3.0 is the Safe Navigation Operator(&.).

1
2
3
4
5
# Good
# Using the safe navigation operator (&.)
if account&.owner&.address
# ...
end

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
2
3
4
5
6
7
8
9
10
11
12
x = {
foo: {
bar: [ 'a', { baz: 'x' } ]
}
}

# dig from hash.
x.dig(:foo, :bar) # => [ 'a', { baz: 'x' } ]

# dig from hash and embed array, hash.
x.dig(:foo, :bar, 1, :baz) # => "x"
x.dig(:foo, :wronk, 1, :baz) # => nil

References

[1] Syntactic sugar methods in Ruby | AppSignal Blog - https://blog.appsignal.com/2018/02/20/ruby-magic-syntactic-sugar-methods.html

[2] The Safe Navigation Operator (&.) in Ruby – Georgi Mitrev - https://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

[3] Ruby 2.3 brings Array#dig and Hash#dig - makandra dev - https://makandracards.com/makandra/41180-ruby-2-3-brings-array-dig-and-hash-dig