有人可以解释一下Ruby中这3个(显然)相同的例子之间的区别吗?
代码#1
class User < ActiveRecord::Base
def something
....
end
end
代码#2
class User < ActiveRecord::Base
def User.something
....
end
end
代码#3
class User < ActiveRecord::Base
def self.something
....
end
end
答案 0 :(得分:0)
class User < ActiveRecord::Base
def something
# ....
end
def User.something
end
def self.something
end
end
这里第一个是实例方法,只能用User
实例调用ex: User.new.something
另外两种方法是类方法(也称为单例方法)。哪个只能在User类上调用。
ex: User.something
还有一种方法可以调用类方法
class User < ActiveRecord::Base
class << self
def something
"wolf"
end
end
end
答案 1 :(得分:0)
class User < ActiveRecord::Base
def something
....
end
end
答案:此方法可用于此类的实例/对象的单例类。
class User < ActiveRecord::Base
def User.something
....
end
end
class User < ActiveRecord::Base
def self.something
....
end
end
class User < ActiveRecord::Base
class << self
def something
.......
end
end
end
最后3种方法被定义为类级别。基本上,类是对象,所以它们只能以编程方式提供给那些类。如果您不介意我建议您观看以下视频。 The Ruby Object Model and Metaprogramming