Ruby类方法与本征类中的方法 [英] Ruby Class Methods vs. Methods in Eigenclasses

查看:217
本文介绍了Ruby类方法与本征类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类的方法和方法在该类的本征类(或元类)只有两种方式来定义一个东西?

Are class methods and methods in the eigenclass (or metaclass) of that class just two ways to define one thing?

否则有什么区别?

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

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

$ b b

Do Xa Xb 以任何方式表现不同?

Do X.a and X.b behave differently in any way?

我知道我可以通过打开特征类来覆盖或别名类方法:

I recognize that I can overwrite or alias class methods by opening the eigenclass:

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_ *方法,例如:

The two methods are equivalent. The 'eigenclass' version is helpful for using the attr_* methods, for example:

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

这篇关于Ruby类方法与本征类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆