2016-03-28 11 views
0

を私は次のクラスを作成しました:残念ながらdefine_methodはゼロのため、未定義のメソッド `各」を返す:NilClass

decor = Decorator.new({ highlight: 'light', color: 'green' }) 
if decor.highlight? 
    puts decor.highlight 
end 
if decor.color? 
    puts decor.color 
end 

、私は試してみてください。私は次の操作を行うことができるようにしたい

class Decorator < OpenStruct 
    def initialize(options={}) 
     define_predicate options 
     super(options) 
    end 

    def define_predicate(options) 
     options.each do |k,v| 
     define_method "#{k}?" do 
      v.present? 
     end 
     end 
    end 
    end 

をDecoratorクラスを初期化すると、次のエラーが発生します。

NoMethodError: undefined method `each' for nil:NilClass 
    from /Users/donato/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/ostruct.rb:245:in `inspect' 
    from /Users/donato/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/ostruct.rb:187:in `method_missing' 
    from (irb):16:in `block in define_predicate' 
    from (irb):15:in `each' 
    from (irb):15:in `define_predicate' 
    from (irb):10:in `initialize' 
    from (irb):22:in `new' 

なぜdefine_methodがこのエラーをスローしますか?

これは動作します:

class Decorator < OpenStruct 
    def initialize(options={}) 
     Decorator.define_predicate options 
     super(options) 
    end 

    def self.define_predicate(options) 
     options.each do |k,v| 
     define_method "#{k}?" do 
      v.present? 
     end 
     end 
    end 
    end 
+0

'define_method'はエラーを発生させますが、それをスローしません。 'OpenStruct'は' define_method'という属性を見つけることができないので、 'method_missing'でエラーを投げています。ヒント:['define_method'](http://ruby-doc.org/core-2.3.0/Module-.html#method-i-define_method)はどこから来ていますか?それはあなたのインスタンスメソッドではありませんクラス?私はドアを急いでいる、または私はもっと言うだろう。 –

+0

私はdefine_methodがModuleで定義されているので、クラスコンテキストで使用する必要があります。 – Donato

+0

正確な重複はないかもしれませんが、回答は同じです:['define_singleton_method'](http://ruby-doc.org/core-2.3.0/Object.html#method-i-define_singleton_method) 'define_method'を使用しようとしています。 –

答えて

0

define_methodは、クラスメソッドです。最初のケースでは、オブジェクトインスタンスに対してdefine_methodがトリガされます。

関連する問題