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!

Advertisements

One thought on “Code quickie: instance_variable_set name in ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s