Something about Instance Method and Class Method

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值