Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Is it possible to set the value of a instance variable where the instance variable is named via a string?

Tags:

ruby

Not sure what this pattern is called, but here is the scenario:

class Some
   #this class has instance variables called @thing_1, @thing_2 etc.
end

Is there some way to set the value of the instance variable where the instance variable name is created by a string?

Something like:

i=2
some.('thing_'+i) = 55 #sets the value of some.thing_2 to 55
like image 680
Zabba Avatar asked Dec 06 '10 19:12

Zabba


2 Answers

Search for “instance_variable” on Object:

some.instance_variable_get(("@thing_%d" % 2).to_sym)
some.instance_variable_set(:@thing_2, 55)

This pattern is referred to as “fondling”; it can be a better idea to explicitly use a Hash or Array if you will be computing keys like this.

like image 146
Josh Lee Avatar answered Nov 14 '22 13:11

Josh Lee


You can generate accessor methods for those instance variables and then just send setters:

class Stuff
  attr_accessor :thing_1, :thing_2
end

i = 1
s = Stuff.new
s.send("thing_#{i}=", :bar)
s.thing_1 # should return :bar
like image 20
Eimantas Avatar answered Nov 14 '22 14:11

Eimantas