mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Safe Navigation Operator as a ruby til.
This commit is contained in:
@@ -209,6 +209,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Question Mark Operator](ruby/question-mark-operator.md)
|
- [Question Mark Operator](ruby/question-mark-operator.md)
|
||||||
- [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.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)
|
- [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)
|
- [Set RVM Default Ruby](ruby/set-rvm-default-ruby.md)
|
||||||
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
|
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
|
||||||
- [Summing Collections](ruby/summing-collections.md)
|
- [Summing Collections](ruby/summing-collections.md)
|
||||||
|
|||||||
25
ruby/safe-navigation-operator.md
Normal file
25
ruby/safe-navigation-operator.md
Normal 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/)
|
||||||
Reference in New Issue
Block a user