DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on • Edited on

Stop checking if it's nil in Rails

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 &
Alt Text

10&.to_s  # => "10"
nil&.to_s #=> nil

πŸ”— Parent Note

Top comments (0)