我正在尝试使用method_missing方法将美元转换为不同的货币。
class Numeric
@@currency={"euro"=>2, "yen"=>6}
def method_missing(method_id,*args,&block)
method_id.to_s.gsub!(/s$/,'') #get rid of s in order to handle "euros"
@@currency.has_key?(method_id) ? self*@@currency[method_id] : super
end
end
> 3.euro #expect to return 6
NoMethodError: undefined method 'euro' for 3:Fixnum
from (pry):24:in 'method_missing'
> 3.euros #expect to return 6
NoMethodError: undefined method 'euros' for 3:Fixnum
from (pry):24:in 'method_missing'
我猜测
3.euro
无法工作的原因是:euro.to_s.gsub!(/s$/,'')
返回了nil
。我不确定为什么会出现“no method error”的错误。谢谢任何帮助。
:sym.to_s
,则会生成全新的字符串对象“sym”。因此,现在如果您在“sym”上使用bang方法,如#gsub!
,则不应影响:sym
。a = :sym a.to_s.sub!('s' ,'d') # => "dym" a # => :sym
- Arup Rakshit