下面的代码在Ruby中是什么意思?
||=
它的语法有什么意义或原因吗?
下面的代码在Ruby中是什么意思?
||=
它的语法有什么意义或原因吗?
当前回答
简洁完整的回答
a ||= b
计算方法与下面每一行相同
a || a = b
a ? a : a = b
if a then a else a = b end
-
另一方面,
a = a || b
计算方法与下面每一行相同
a = a ? a : b
if a then a = a else a = b end
-
编辑:正如AJedi32在评论中指出的那样,这只在以下情况下成立:A是一个已定义变量。2. 计算一次时间和两次时间不会导致程序或系统状态的差异。
其他回答
这就像延迟实例化。 如果变量已经定义,它将获取该值,而不是重新创建该值。
它的意思是或等于。它检查左边的值是否有定义,然后使用它。如果不是,使用右边的值。您可以在Rails中使用它来缓存模型中的实例变量。
一个基于rails的快速示例,我们创建了一个函数来获取当前登录的用户:
class User > ActiveRecord::Base
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
end
它检查是否设置了@current_user实例变量。如果是,它将返回该值,从而节省数据库调用。但如果没有设置,则执行调用,然后将@current_user变量设置为该值。这是一种非常简单的缓存技术,但非常适合在应用程序中多次获取相同的实例变量。
准确地说,||= b意味着“如果a是未定义的或假的(false或nil),将a设置为b并求值为(即返回)b,否则求值为a”。
其他人经常试图用||= b等价于|| a = b或a = a || b来说明这一点。这些等价有助于理解这个概念,但要注意,它们并非在所有条件下都是准确的。请允许我解释:
a ||= b ⇔ a || a = b? The behavior of these statements differs when a is an undefined local variable. In that case, a ||= b will set a to b (and evaluate to b), whereas a || a = b will raise NameError: undefined local variable or method 'a' for main:Object. a ||= b ⇔ a = a || b? The equivalency of these statements are often assumed, since a similar equivalence is true for other abbreviated assignment operators (i.e. +=,-=,*=,/=,%=,**=,&=,|=,^=,<<=, and >>=). However, for ||= the behavior of these statements may differ when a= is a method on an object and a is truthy. In that case, a ||= b will do nothing (other than evaluate to a), whereas a = a || b will call a=(a) on a's receiver. As others have pointed out, this can make a difference when calling a=a has side effects, such as adding keys to a hash. a ||= b ⇔ a = b unless a?? The behavior of these statements differs only in what they evaluate to when a is truthy. In that case, a = b unless a will evaluate to nil (though a will still not be set, as expected), whereas a ||= b will evaluate to a. a ||= b ⇔ defined?(a) ? (a || a = b) : (a = b)???? Still no. These statements can differ when a method_missing method exists which returns a truthy value for a. In this case, a ||= b will evaluate to whatever method_missing returns, and not attempt to set a, whereas defined?(a) ? (a || a = b) : (a = b) will set a to b and evaluate to b.
好的,好的,那么||= b等于什么?有办法在Ruby中表达这一点吗?
好吧,假设我没有忽略任何东西,我相信||= b在功能上等价于……(击鼓声)
begin
a = nil if false
a || a = b
end
坚持住!这不是第一个前面有noop的例子吗?嗯,不完全是。还记得我之前说的||= b只有当a是一个未定义的局部变量时,||= b才不等于|| a = b吗?如果为false,则a = nil确保a永远没有定义,即使这一行永远不会执行。Ruby中的局部变量是词法范围的。
一个常见的误解是,||= b并不等同于a = a || b,但它的行为就像|| a = b。
但这里有一个棘手的情况。如果a未定义,则|| a = 42将引发NameError,而||= 42将返回42。所以,它们似乎不是等价的表达式。
b = 5
a ||= b
这句话的意思是:
a = a || b
这将是
a = nil || 5
所以最后
a = 5
现在如果你再调用这个:
a ||= b
a = a || b
a = 5 || 5
a = 5
b = 6
现在如果你再调用这个:
a ||= b
a = a || b
a = 5 || 6
a = 5
如果你观察,b的值不会被分配给a, a仍然有5。
它是Ruby中用来加快访问速度的一种记忆模式。
def users
@users ||= User.all
end
这句话的意思是:
@users = @users || User.all
第一次调用这个方法时,你会调用数据库。
以后对该方法的调用将只返回@users实例变量的值。