类方法中的Ruby实例引用?

时间:2012-10-23 05:28:00

标签: ruby

我正在尝试从文件中填写类实例的类变量,而我设法解决如何执行此操作的唯一方法就是

a=Thing.new
File.read("filename.ext").each_line do |arguments| #this will => things like @variable=str\n
eval( "a.instance_eval {" + arguments.chop + "}")   #hence the awkward eval eval chop
end

我发现的唯一问题是,在尝试在类方法中实现这一点时(为了多次实例),我不知道如何实现这一点:

class Thing
attr_accessor :variable

 def self.method
  File.read("filename.ext").each_line do |arguments|
   eval("instance.instance_eval{" + arguments.chop + "}")   #this line
  end
 end
end

即,对调用该方法的实例的引用。在这种情况下,自我只会成为事情,所以有什么方法可以做到这一点吗?更有针对性的可能是更好的方式来解决这个问题。我昨晚才刚刚学会了红宝石,所以我没有机会看到一些更简洁的技巧,而且我的语言成熟度有点新鲜了。

对于上下文,Thing是游戏中的一个角色,从保存文件加载其基本值。

1 个答案:

答案 0 :(得分:1)

嗯,首先,请看Marshal。它专门用于将数据结构转储为序列化格式并将其加载回来。

说,如果你想坚持你的方向,那就尝试这样的事情:

class Thing
  attr_accessor :variable

  def self.method
    File.read("filename.ext").each_line do |arguments|
      ivar, val = arguments.strip.split("=", 2)
      instance.instance_variable_set(ivar, val)
    end
  end
end

#instance_variable_set允许你......好吧,按名称在对象上设置实例变量。不需要丑陋的评估!

通过示范:

class Foo
  attr_accessor :bar
end

foo = Foo.new
foo.instance_variable_set("@bar", "whatzits")
puts foo.bar # => whatzits
相关问题