Ruby 2.3.0 safe operator
Ruby 2.3.0 has been released (yey!) and with it one of the coolest features of all time. The safe operator.
The safe operator is just some simpler way to do something that we already have in rails. But now this feature is in the core language.
Now show me the code. On rails is pretty common to have errors like this
> @current_user.trophy.title
# NoMethodError: undefined method `title' for nil:NilClass
On this little fix solves this problem
> @current_user.trophy.try(:title)
# nil
There's no error raised if one uses the try operator. That's pretty cool. Unfortunately It is limited to the rails stack. Now with the new ruby 2.3.0 is possible to use the safe operator which was attributed to the &
key word.
Now the same behaviour we can extend with
> @current_user.trophy.&title
# nil
Now is much safer to write code in plain ruby.