| 本帖最后由 orzfly 于 2012-3-11 15:15 编辑 
 @fux2@ky52879@晴兰
 
 let's trace
 
 $sm=[]class Class  def sm(sym)    self.class_eval do      return if (@@__smed||=[]).include?(sym)      @@__smed.push sym      alias :"old_#{sym}" :"#{sym}"      define_method sym do |*args, &block|        $sm << [self, sym, *args]        old = $sm[-1]        old.push self.send(:"old_#{sym}", *args, &block)        old[-1]      end    end  endend$sm=[] class A  attr_accessor :size  def initialize    @size = 0  end  def size    return @size / 2  end  sm :size  sm :size=end$a = A.new$a.size += 1$a.size += 1$a.size += 1$a.size += 1$a.size += 1p $a.sizeputs "\nsm result: "puts $sm.map { |j| j.join "\t" }.join "\n"
$sm=[] 
class Class 
  def sm(sym) 
    self.class_eval do 
      return if (@@__smed||=[]).include?(sym) 
      @@__smed.push sym 
      alias :"old_#{sym}" :"#{sym}" 
      define_method sym do |*args, &block| 
        $sm << [self, sym, *args] 
        old = $sm[-1] 
        old.push self.send(:"old_#{sym}", *args, &block) 
        old[-1] 
      end 
    end 
  end 
end 
$sm=[] 
  
class A 
  attr_accessor :size 
  def initialize 
    @size = 0 
  end 
  def size 
    return @size / 2 
  end 
  sm :size 
  sm :size= 
end 
$a = A.new 
$a.size += 1 
$a.size += 1 
$a.size += 1 
$a.size += 1 
$a.size += 1 
p $a.size 
puts "\nsm result: " 
puts $sm.map { |j| j.join "\t" }.join "\n" 
 the result of /2 is
 the result of /2.0 is复制代码sm result: 
#<A:0x1a4c588>        size        0
#<A:0x1a4c588>        size=        1        1
#<A:0x1a4c588>        size        0
#<A:0x1a4c588>        size=        1        1
#<A:0x1a4c588>        size        0
#<A:0x1a4c588>        size=        1        1
#<A:0x1a4c588>        size        0
#<A:0x1a4c588>        size=        1        1
#<A:0x1a4c588>        size        0
#<A:0x1a4c588>        size=        1        1
#<A:0x1a4c588>        size        0
由此可知 size += 1 被翻译成了 size = size + 1 来执行复制代码
sm result: 
#<A:0x169c578>        size        0.0
#<A:0x169c578>        size=        1.0        1.0
#<A:0x169c578>        size        0.5
#<A:0x169c578>        size=        1.5        1.5
#<A:0x169c578>        size        0.75
#<A:0x169c578>        size=        1.75        1.75
#<A:0x169c578>        size        0.875
#<A:0x169c578>        size=        1.875        1.875
#<A:0x169c578>        size        0.9375
#<A:0x169c578>        size=        1.9375        1.9375
#<A:0x169c578>        size        0.96875
 |