Created
October 5, 2022 10:32
-
-
Save thiagofm/15e6f5b2dc50a16a10e23a10138854ba to your computer and use it in GitHub Desktop.
Avoiding nils in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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