假设,我有以下课程:

class MyClass
  attr_accessor :vars

  def initialize
    @vars = []
  end

  def add_var var
    @vars << var
  end

end

我想这样访问内部变量:
x = MyClass.new('root')
x.add_var 'test'
x.add_var 'something'
x.add_var Myclass.new('google')
x.google.add_var 'nice'

puts x.test
puts x.something
puts x.google.nice

一般来说,有可能吗?我该在哪里挖?

最佳答案

它是标准Ruby库的一部分,叫做OpenStruct:

#!/usr/bin/ruby1.8

require 'ostruct'

x = OpenStruct.new
x.google = OpenStruct.new
x.google.nice = 'Nice.  Real nice'
p x.google.nice        # "Nice.  Real nice"

也可以在构造函数中初始化属性:
x = OpenStruct.new(:google=>OpenStruct.new(:nice=>'Nice.  Real nice'))
p x.google.nice    # => "Nice.  Real nice"

关于ruby - Ruby访问魔术,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2108986/

10-13 08:03