Ruby define#u方法返回未定义的方法'each';零级:零级
我创建了以下类:Ruby define#u方法返回未定义的方法'each';零级:零级,ruby,Ruby,我创建了以下类: 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?
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_方法抛出这个错误
这项工作:
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
class Decorator
定义方法是类方法。在第一种情况下,在对象实例上触发define_方法 define\u方法
触发错误,但不会抛出错误OpenStruct
通过method\u missing
抛出错误,因为它找不到名为define\u method
的属性。提示:它从何而来,为什么不是类中的实例方法?我急着出门,或者我想说更多。我明白了,define_方法是在模块中定义的,所以我必须在类上下文中使用。可能不是完全相同,但答案是相同的:在您试图使用define_方法的地方使用。
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