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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With