From Nested Hash
🤔 Umm,
Sometimes, I see like this code. The first row guards from the case of session[:user] == nil
.
if session[:hoge]
fuga = session[:hoge][:fuga]
piyo = session[:hoge][:piyo]
end
But, this way is not straight forward. How we cut the first line. The logic is NOT THE BUSSINESS LOGIC!!
🦄 Clear
Hash#dig makes it simple. It checks the key-value is existed or not, and if it's not existed, dig returns nil.
It's similar of the .&
method.
fuga = session.dig(:hoge,:fuga)
piyo = session.dig(:hoge,:piyo)
👍 From Object
The safe navigate operator &.
(We Japanese call it alone operator. It looks so).
This picture is inversion of &
10&.to_s # => "10"
nil&.to_s #=> nil
Top comments (0)