Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby instance reference in class method?

Tags:

ruby

I'm trying to fill in class variables for a class instance from a file, and the only way I've managed to figure how to do this is something like

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

The only problem I've found is that in trying to impliment this in a class method (to do this for several instances in a go), I don't know how to make this happen:

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

namely, the reference to the instance calling the method. self will just just be Thing in this case, so is there any way to do this? More pertinent might be a better way to go about this overall. I only just learned ruby last night, so I haven't had an opportunity to see some of the neater tricks that are to be had, and my language maturity is a little fresh yet as a result.

For context, Thing is a character in a game, loading its base values from a savefile.

like image 607
Ryan Wood Avatar asked Jul 02 '26 14:07

Ryan Wood


1 Answers

Well, first off, take a look at Marshal. It's specifically used for dumping data structures to serialized formats and loading them back.

The said, if you want to persist in your direction, then try something like this:

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 allows you to...well, set instance variables on an object by name. No ugly eval necessary!

By way of demonstration:

class Foo
  attr_accessor :bar
end

foo = Foo.new
foo.instance_variable_set("@bar", "whatzits")
puts foo.bar # => whatzits
like image 127
Chris Heald Avatar answered Jul 04 '26 04:07

Chris Heald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!