diff --git a/README.md b/README.md index 62bc3b3..8d2962c 100644 --- a/README.md +++ b/README.md @@ -209,6 +209,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Question Mark Operator](ruby/question-mark-operator.md) - [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.md) - [Replace The Current Process With An External Command](ruby/replace-the-current-process-with-an-external-command.md) +- [Safe Navigation Operator](ruby/safe-navigation-operator.md) - [Set RVM Default Ruby](ruby/set-rvm-default-ruby.md) - [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md) - [Summing Collections](ruby/summing-collections.md) diff --git a/ruby/safe-navigation-operator.md b/ruby/safe-navigation-operator.md new file mode 100644 index 0000000..70abe2e --- /dev/null +++ b/ruby/safe-navigation-operator.md @@ -0,0 +1,25 @@ +# Safe Navigation Operator + +With the release of Ruby 2.3, the *safe navigation operator* (`&.`) is now +available. This addition to the Ruby language allows you to collapse all +those pesky `nil` checks into the accessor call they are guarding. Consider +this snippet of common Ruby code: + +```ruby +if user && user.authenticate(params[:password]) + # proceed with logged in user +end +``` + +With the *safe navigation operator*, the predicate can now be collapsed: + +```ruby +if user&.authenticate(params[:password]) + # proceed with logged in user +end +``` + +If `user` is `nil`, then the predicate will evaluate to `false` and the body +of the if-statement will be passed over. + +[Source](http://nithinbekal.com/posts/ruby-2-3-features/)