我创建了以下类:
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
我希望能够做到以下几点:
decor = Decorator.new({ highlight: 'light', color: 'green' })
if decor.highlight?
puts decor.highlight
end
if decor.color?
puts decor.color
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 :(得分:0)
define_method是一个类方法。在第一种情况下,在对象实例上触发define_method。