本文介绍了Ruby 2.3 安全导航操作符 '&.和“尝试!"来自 ActiveSupport 的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 2.3 中的安全运算符 &. 和 ActiveSupport 中的 try! 方法是否可以互换?如果不是,它们之间有什么区别?

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?

推荐答案

一个关键的区别是 try! 是一个额外的方法调用,而 &. 不是.我可以想到这造成的一个(公认的人为)差异

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

但是如果(在新的 irb 会话中 - 这很重要)我愿意

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)

在这种情况下 $& 仍在设置,但它是在 try! 方法中设置的,因此您永远看不到它.

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

额外的方法调用也使 try 变慢(在快速基准测试中几乎是一个数量级),尽管在任何实际使用中,您调用的实际方法的成本应该使

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!

这篇关于Ruby 2.3 安全导航操作符 '&.和“尝试!"来自 ActiveSupport 的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:23