How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?

后端 未结 2 1456
不思量自难忘°
不思量自难忘° 2020-12-16 02:59

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

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


        
相关标签:
2条回答
  • 2020-12-16 03:22

    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
    
    0 讨论(0)
  • 2020-12-16 03:23

    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.

    0 讨论(0)
提交回复
热议问题