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

cri*_*spy 14 ruby overriding class class-method eigenclass

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

否则,有什么区别?

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

  # eigenclass method
  class << self
    def b
      "b"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

难道X.aX.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"
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 11

这两种方法是等价的.'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>]
Run Code Online (Sandbox Code Playgroud)

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

Foo.define_singleton_method :bim do "bam!" end
Run Code Online (Sandbox Code Playgroud)


age*_*217 6

在Ruby中,确实没有类方法这样的东西.因为Ruby中的所有东西都是对象(包括类),所以当你说def self.class_method,你只是在类的实例上定义一个单例方法Class.所以回答你的问题,说

class X
  def self.a
    puts "Hi"
  end

  class << self
    def b
      puts "there"
    end
  end
end

X.a # => Hi
X.b # => there
Run Code Online (Sandbox Code Playgroud)

是两种说同样的方式.这两种方法都只是在你的Class对象实例中定义的singeton(eigen,meta,ghost或者你想要称之为的任何方法)方法X.这个主题是元编程的一部分,这是一个有趣的话题,如果你已经使用Ruby一段时间了,你应该看看.实用程序员有一关于元编程的好书,如果你对这个主题感兴趣,你一定要看看.

  • 不同意"没有班级方法".Smalltalk已经存在了很长时间,也是纯粹的OO,它们一直使用类方法术语.说类方法比'singleton'更容易混淆,因为后者是设计模式而不是语言的属性. (2认同)