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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With