关闭

Something about Instance Method and Class Method

标签: classmethodsobjectaccessruby
219人阅读 评论(0) 收藏 举报
If you wanted to define several methods for
class Array, you'd write

class Array
  [define methods here]
end

and all instances of Array can now use your methods

similarly, if you want to define several methods for an object's singleton
class, you write

class << object
  [define methods here]
end

and all instances of object's singleton class (i.e., just object) can
now access the methods.

As for class methods - well, a class is just an instance of class Class.
Therefore, it has methods which are instance methods of Class. You can
add in methods by saying

class Class
  [define methods here]
end

and all classes will now have the new class methods. If you want class
methods for a single class, you are actually tacking on methods to an
object, in much the same way as "def a.newmethod" would. So you can use
that syntax:

def Array.newmethod1
  [define]
end

or you can say

class << Array
  [define]
end

or, if you are already *in* class Array and defining instance methods,
you can highilght the fact that you're working in the same conceptual
space by taking advantage of Ruby's setting 'self' to 'Array' when you say
'class Array', and writing

class Array
  def instancemethod
    [define]
  end

  class << self
    def classmethod
      [define]
    end
  end
end

There's no arcane magic going on here - self is an object of class
Class, and in this case it has the value Array.

Try the following:

class Array
  p self
  p self.class
  p self.id
end

class << Array
  p self
  p self.class
  p self.id
end

class Array
  class << self
    p self
    p self.class
    p self.id
  end
end

a = Array.new
class << a
  p self
  p self.class
  p self.id
end

and, to prove that singleton classes are being created, even though they
all say Array,

b = Array.new
class << b
  p self
  p self.id
end
   
p Array.id

0
0

猜你在找
【套餐】Hadoop生态系统零基础入门
【套餐】嵌入式Linux C编程基础
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【套餐】深度学习入门视频课程——唐宇迪
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】计算机视觉原理及实战——屈教授
【直播】机器学习之凸优化——马博士
【直播】机器学习&数据挖掘7周实训--韦玮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21099次
    • 积分:310
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:19篇
    • 译文:0篇
    • 评论:3条
    最新评论