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

后端 未结 2 1461
不思量自难忘°
不思量自难忘° 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题