程式扎記: [ 常見問題 ] How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?

標籤

2014年11月13日 星期四

[ 常見問題 ] How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?

Source From Here
Question
This throws me a SystemStackError in 1.9.2 Ruby
  1. class Fixnum  
  2.   def +(other)  
  3.    self + other * 2  
  4.   end  
  5. end  
but there is no super for + (based on other errors). How can I access the original + functionality?

How-To
Use alias_method. Alias Fixnum's + to something else, then refer to it in the new +:
  1. class Fixnum  
  2.   alias_method :old_add, :+  
  3.   def +(other)  
  4.     self.old_add(other) * 2  
  5.   end  
  6. end  
Supplement
API:alias_method


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!