单例方法与类方法 [英] Singleton method vs. class method

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

问题描述

类方法和单例方法是一样的还是不同的?这是一个例子.

Are class method and singleton method doing the same or different? Here is an example.

class C
  def self.classmethod
    puts "class method #{self}"
  end
end

C.classmethod  # class method C
c = C.new

def c.singletonmethod
  puts "instance method #{self}"
end

c.singletonmethod  # instance method #<C:0x0000000118ed08>

推荐答案

Ruby 中发生的大部分事情都涉及到类和模块,其中包含实例方法的定义

Most of what happens in Ruby involves classes and modules, containing definitions of instance methods

class C
  def talk
    puts "Hi!"
  end
end

c = C.new
c.talk
Output: Hi!

但是正如您之前看到的(甚至比您看到类中的实例方法还要早),您也可以直接在单个对象上定义单例方法:

But as you saw earlier (even earlier than you saw instance methods inside classes), you can also define singleton methods directly on individual objects:

obj = Object.new
def obj.talk
  puts "Hi!"
end
obj.talk
#Output: Hi!

当您在给定对象上定义单例方法时,只有该对象可以调用该方法.如您所见,最常见的单例方法是类方法——一种单独添加到 Class 对象的方法:

When you define a singleton method on a given object, only that object can call that method. As you’ve seen, the most common type of singleton method is the class method—a method added to a Class object on an individual basis:

class Car
  def self.makes
    %w{ Honda Ford Toyota Chevrolet Volvo }
  end
end

但是任何对象都可以添加单例方法.在每个对象的基础上定义方法驱动行为的能力是 Ruby 设计的标志之一.

But any object can have singleton methods added to it. The ability to define method- driven behavior on a per-object basis is one of the hallmarks of Ruby’s design.

单例类是匿名的:虽然它们是类对象(类 Class 的实例),但它们会自动出现而无需命名.尽管如此,您可以打开单例类的类定义主体,并像使用常规类一样向其中添加实例方法、类方法和常量.

Singleton classes are anonymous: although they’re class objects (instances of the class Class ), they spring up automatically without being given a name. Nonetheless, you can open the class-definition body of a singleton class and add instance methods, class methods, and constants to it, as you would with a regular class.

注意:

每个对象都有两个类:

■ 实例所属的类

■ 它的单例类

1:Ruby 对象模型和元编程有关的详细信息单例方法 vs. 类方法 ruby​​

1: The Ruby Object Model and Metaprogramming For detail info about singleton method vs. class method ruby

2:元编程 - 扩展 Ruby 以获得乐趣和利润 - 作者 戴夫·托马斯

2: MetaProgramming - Extending Ruby for Fun and Profit - by Dave Thomas

希望对你有帮助!!!

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

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