Ruby 类方法与特征类中的方法

2024-04-03

类方法和该类的特征类(或元类)中的方法只是定义一件事的两种方法吗?

否则的话,有什么区别呢?

class X
  # class method
  def self.a
    "a"
  end

  # eigenclass method
  class << self
    def b
      "b"
    end
  end
end

Do X.a and X.b在任何方面都有不同的行为?

我认识到我可以通过打开特征类来覆盖或别名类方法:

irb(main):031:0> class X; def self.a; "a"; end; end
=> nil
irb(main):032:0> class X; class << self; alias_method :b, :a; end; end
=> #<Class:X>
irb(main):033:0> X.a
=> "a"
irb(main):034:0> X.b
=> "a"
irb(main):035:0> class X; class << self; def a; "c"; end; end; end
=> nil
irb(main):036:0> X.a
=> "c"

这两种方法是等效的。 “eigenclass”版本对于使用 attr_* 方法很有帮助,例如:

class Foo
  @instances = []
  class << self;
    attr_reader :instances
  end
  def initialize
    self.class.instances << self
  end
end

2.times{ Foo.new }
p Foo.instances
#=> [#<Foo:0x2a3f020>, #<Foo:0x2a1a5c0>]

您还可以使用define_singleton_method在类上创建方法:

Foo.define_singleton_method :bim do "bam!" end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby 类方法与特征类中的方法 的相关文章

随机推荐