Skip to content

Instantly share code, notes, and snippets.

@thiagofm
Created October 5, 2022 10:32
Show Gist options
  • Save thiagofm/15e6f5b2dc50a16a10e23a10138854ba to your computer and use it in GitHub Desktop.
Save thiagofm/15e6f5b2dc50a16a10e23a10138854ba to your computer and use it in GitHub Desktop.
Avoiding nils in Ruby
# Using OpenStruct to mimic an object with the 'posts method'
user = OpenStruct.new(posts: [:post1, :post2])
# Using if user as a nil checker
user.posts if user
# => [:post1, :post2]
# Can be replaced with the safe navigation operator
user&.posts
# => [:post1, :post2]
# What about hashes?
hash = { user: { posts: [:post1, :post2]}}
# Using user[:posts] as a nil checker
hash[:user][:posts] if hash[:user] && hash[:user][:posts]
# => [:post1, :post2]
# Using the Hash#dig method
hash.dig(:user, :posts)
# That's it! 😁
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment