class User < ActiveRecord::Base
...
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
...
end
为什么第3行self[column]
中的代码有效?由于self
是User
类的实例,因此它不应该是self.column而不是column吗?我认为var[index]
是数组处理的方式,不是吗?
答案 0 :(得分:3)
self[column]
只是撰写self.[](column)
的另一种方式。其中[]
是方法名称,column
是参数。 ActiveRecord::Base
实施[]
,因此您可以像Array
一样访问列。
class Example
def [](arg)
return "foo"
end
end
x = Example.new
x[1] # => "foo"
x[3] # => "foo"
x["bar"] # => "foo"