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

血红的双手。 提交于 2019-11-27 16:38:18

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9745122/how-can-i-redefine-fixnums-plus-method-in-ruby-and-keep-original-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!