在 Michael Hartl 的教程中,他有一个 模块 SessionsHelper
,它有一个名为 current_user=
的方法,它接受一个参数并将其分配给 @current_user
。然后,他使用类似 current_user = User.first
的行在他的程序中的各种其他方法中调用它。
我的问题是我们怎么知道 current_user=
方法被调用了——在我看来实际发生的是一个名为 current_user
是当场创建的,给定 User.first
的值,然后当函数关闭时该变量消失。
我还通过创建以下代码简单地对此进行了测试:
def x= val
puts "method called"
end
x = 46
puts x
此代码片段只是在屏幕上打印 46 - 根本不会调用函数 x=
。那么 Michael Hartl 的教程中的 current_user=
方法在做什么,他是如何调用该函数的?
最佳答案
这是因为 Ruby 将可作为简单变量读取的表达式视为简单变量。你可以用这段代码看到它:
def x
10
end
print x #=> 10
x = 5
print x #=> 5
print x() #=> 10
print self.x #=> 10
这个也是一样的。看:
def x=(a)
print a
end
x = 8 #=> Variable 'x' assigned to 8
x=(8) #=> The same
self.x = 8 #=> Function called
还要记住赋值函数(就像最后一个)不能返回任何值,返回值总是最后一个参数。
def x=(a)
return a+1
end
var = (self.x = 8) #=> Function called; Variable 'var' assigned to 8
关于ruby - Rails——使用末尾带有等号的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352468/