[英]How can I get ruby's "Date.end_of_week(:monday)" method to work with a fixnum? e.g. "Date.end_of_week(1)"
[英]How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?
這引發了我在1.9.2 Ruby中的SystemStackError(
但在Rubinius中工作
):
class Fixnum
def +(other)
self + other * 2
end
end
但是沒有super
for +
(基於其他錯誤)。
如何訪問原始+
功能?
使用alias_method
。 別名Fixnum
的+
其他東西,然后在新的+
引用它:
class Fixnum
alias_method :old_add, :+
def +(other)
self.old_add(other) * 2
end
end
另一個有趣的方法是將塊傳遞給Fixnum的module_eval
方法。 所以,例如:
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
現在,在我的應用程序中包含FixnumExtend后,我可以這樣做:
2.plus 2
=> 4
81.sqrt
=> 9
我正在使用這種方法來幫助我的OCR引擎識別手寫代碼。 2.div 2
比2/2
更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.