DEV Community

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

Posted on β€’ Edited on

3

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’