Saturday, May 12, 2007

Code quickie: instance_variable_set name in ruby

Normally, you can just set an instance variable to initialize it...but if you're doing some meta programming in Ruby, then you might end up using, eval() or instance_eval(). Or you use instance_variable_set(). But notice! You need the "@" symbol in the first argument:
class SomeClass
def initialize(var_name)
instance_variable_set "@#{var_name}", 0
end
end
Well, it doesn't quite make sense to me, since instance variables implies variables of the instance...So you wouldn't think the call to instance_variable_set requires the "@" symbol in the first argument. Tip!

1 comment:

  1. Anonymous8:09 AM

    Thanks for the useful tip!

    ReplyDelete