我希望能够在我的代码中使用以下构造:
p obj.graph_XYZ
obj.graph_XYZ << obj2
在这里,我想处理以graph_
我可以挂钩到getter,但是即使我使用obj.graph_XYZ << obj2
,method_missing也会选择getter。关于我可能做错的任何输入?
答案 0 :(得分:1)
这样的事可能对你有用吗?
$ irb class A attr_accessor :xyz end => nil a = A.new => #<A:0x0000010096bc88> a.xyz => nil a.xyz << 2 NoMethodError: undefined method `<<' for nil:NilClass from (irb):6 from /Users/iain/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>' a.xyz = [ ] => [] a.xyz << 2 => [2] a.xyz => [2] class A def method_missing( name, *args ) return super( name, *args ) unless name.to_s =~ /^graph/ words = name.to_s.split( "_" ) words.shift # get rid of graph_ # now do what you like # ... if (instance_variable_get "@#{words.first.downcase}").nil? instance_variable_set "@#{words.first.downcase}", [] end (instance_variable_get "@#{words.first.downcase}") end end => nil a = A.new => #<A:0x00000100844a58> a.graph_XYZ => [] a.graph_XYZ << 2 => [2] a.graph_XYZ => [2]