Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between the Ruby 2.3 safe navigation operator '&. and the 'try!' method from ActiveSupport?

Are the safe operator &. from Ruby 2.3 and the try! method from ActiveSupport interchangeable? If they aren't, what are the differences between them?

like image 265
gnerkus Avatar asked Jan 17 '16 23:01

gnerkus


1 Answers

A key difference is that try! is a extra method call, whereas &. is not. I can think of one (admittedly contrived) difference this creates

"1234"&.gsub(/\d/, "a")
$& #=> "1234"

No surprises here - I did a regex match so the regex global variables are set ($& is the matched string).

But if (in a fresh irb session - this is important) I do

"1234".try!(:gsub, /\d+/, "a")
$& #=> nil

Then the regex related globals are nil. This is because these globals aren't really global - they are tied to where the code is called from (the docs call this thread and method-local global variables)

In this case $& is still getting set, but it is being set inside the try! method so you never see it.

The extra method call also makes try slower (pretty much an order of magnitude in a quick benchmark) although in any real usage the cost of the actual method you are calling should dwarf the cost of try!

like image 80
Frederick Cheung Avatar answered Sep 24 '22 02:09

Frederick Cheung