微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ruby类方法与本体类中的方法

该类的本征类(或元类)中的类方法方法只是定义一个东西的两种方式吗?

否则有什么区别?

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

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

X.a和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

原文地址:https://www.jb51.cc/ruby/273452.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐