我试图优化一些代码定义上初始化单的方法,我想上,而不是在检查每一个方法调用一定的价值,定义方法与检查已经预先计算响应,因为这个检查在实例的整个生命中不会改变。使用实例变量
我决定为每个创建的实例定义不同版本的方法。更多或更少的这样:
class TestingSingletonMethodsWithVariable
METHODS = %w(a b c d)
def initialize(favorite_method)
class << self
METHODS.each do |method_name|
if(favorite_method == method_name)
define_method method_name do
puts "#{method_name} its my favorite method"
end
else
define_method method_name do
puts "#{method_name} its not my favorite method"
end
end
end
end
end
end
t = TestingSingletonMethodsWithVariable.new('b')
t.a
t.b
t.c
t.d
# $ ruby test/testing_singleton_methods_with_variable.rb
# test/testing_singleton_methods_with_variable.rb:7:in `initialize': undefined local variable or method `favorite_method' for #<Class:#<TestingSingletonMethodsWithVariable:0x1001a77b8>> (NameError)
# from test/testing_singleton_methods_with_variable.rb:6:in `each'
# from test/testing_singleton_methods_with_variable.rb:6:in `initialize'
# from test/testing_singleton_methods_with_variable.rb:21:in `new'
# from test/testing_singleton_methods_with_variable.rb:21
正在发生的事情是,一些奇怪与变量发生了:变量声明外侧class << self
块是不是里面的变量是可见的。
任何人都可以解释我怎么做我正在寻找的行为?
由于
我认为有一些与你的例子混淆。在主题行中提到了实例变量,但是您发布的代码中没有任何实例变量。 – 2010-11-16 17:56:40