我正在尝试使用 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'
I guess 3.euro
不工作,因为:euro.to_s.gsub!(/s$/,'')
回报nil
。我不确定为什么它不返回任何方法错误。
谢谢你的帮助。
When 方法缺失将被调用,然后euro
将被分配给method_id
as a symbol。但你的@@currency
hash 将所有键保存为字符串,您需要将它们转换为symbols.
method_id.to_s.gsub!(/s$/,'')
没有办法改变实际的对象method_id
。因为method_id.to_s
会给你一个新的string对象,以及#gsub!
只会致力于此。你不可能改变method_id
,它保持原样。更好用non-bang一,因为如果没有进行任何更改,它会给您实际的对象,或者如果发生更改,则更改对象,那么您需要将此返回值分配给一个新变量。
和你的@@currency
, @@currency.has_key?(method_id)
评价为false
and super
class method_missing
已被调用。为什么?作为method_id
没有转换成字符串,这可能会发生您期望的情况。
但是,如果您想对两者都做出回应,例如euro
or euros
, then
class Numeric
@@currency={"euro" => 2, "yen" => 6}
def method_missing(method_id,*args,&block)
#get rid of s in order to handle "euros"
new_method_id = method_id.to_s.gsub(/s$/,'')
@@currency.has_key?(new_method_id) ? self*@@currency[new_method_id] : super
end
end
3.euros # => 6
3.euro # => 6
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)