9

This throws me a SystemStackError in 1.9.2 Ruby (but works in Rubinius):

class Fixnum
  def +(other)
   self + other * 2
  end
end

but there is no super for + (based on other errors).

How can I access the original + functionality?

4

2 回答 2

16

Use alias_method. Alias Fixnum's + to something else, then refer to it in the new +:

class Fixnum
  alias_method :old_add, :+
  def +(other)
    self.old_add(other) * 2
  end
end
于 2012-03-16T22:34:15.327 回答
1

Another interesting approach would be to pass a block to Fixnum's module_eval method. So, for instance:

module FixnumExtend
  puts '..loading FixnumExtend module'

  Fixnum.module_eval do |m|
    alias_method :plus,     :+
    alias_method :min,      :-
    alias_method :div,      :/
    alias_method :mult,     :*
    alias_method :modu,     :%
    alias_method :pow,      :**

    def sqrt
     Math.sqrt(self)
    end

  end

end

Now, after including FixnumExtend throughout my app I can do:

2.plus 2   
=> 4

81.sqrt
=> 9

I am using this approach to help my OCR engine recognize handwritten code. It has an easier time with 2.div 2 than 2/2.

于 2012-04-30T18:22:15.560 回答