如何访问另一个动态创建的 class?

How to access a dynamically created class within another?

我不知道如何访问另一个动态创建的 class。 classes 存储在局部变量中,我想避免使用常量,因为 classes 是在方法中创建的。

def clazzes_and_clazzes
  clazz_one = Class.new do
    def one; 'one'; end
  end
  puts clazz_one.new.one

  clazz_two = Class.new do
    def two
      clazz_one.new.one + ' and ' + clazz_one.new.one
    end
  end
  puts clazz_two.new.two

  clazz_two
end

clazzes_and_clazzes

我希望得到以下输出。

$ ruby snippet.rb
one
one and one

但上面的代码片段引发了以下错误消息。

snippet.rb:9:in `two': undefined local variable or method `clazz_one' for #<#<Class:0x7f2fa401af10>:0x7f2fa401ae98> (NameError)
    from snippet.rb:12:in `clazzes_and_clazzes'
    from snippet.rb:15

我该如何解决这个错误?

当您使用 def 关键字定义方法时,您超出了定义 clazz_one 的范围。相反,您可以使用 define_method 方法,它接受一个块,它是闭包,因此它保留了局部范围:

define_method :two do
  clazz_one.new.one + ' and ' + clazz_one.new.one
end

您可以在此处了解有关 Ruby 范围的更多信息: http://www.sitepoint.com/understanding-scope-in-ruby/