1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Safe Navigation Operator as a ruby til.

This commit is contained in:
jbranchaud
2015-12-27 09:54:04 -06:00
parent 2dd08e0f0b
commit b096a99e26
2 changed files with 26 additions and 0 deletions

View File

@@ -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)

View File

@@ -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/)