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

后端 未结 2 1464
不思量自难忘°
不思量自难忘° 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
    

提交回复
热议问题