Ruby: Is it possible to set the value of an instance variable where the instance variable is called through a string?

Not sure if this template is being called, but here is the script:

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

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

Something like:

 i=2 some.('thing_'+i) = 55 #sets the value of some.thing_2 to 55 
+6
ruby
source share
3 answers

Find "instance_variable" on Object :

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

This pattern is called "caressing"; it may be better to use an explicit hash or array if you compute such keys.

+17
source share

You can create access methods for these instance variables, and then only send seters:

 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 
+2
source share

I was interested in the same thing, so I played with the console. Entertainment:

 class Parent class << self attr_accessor :something def something(value = nil) @something = value ? value : @something end def inherited(subclass) self.instance_variables.each do |var| subclass.instance_variable_set(var, self.instance_variable_get(var)) end end end attr_accessor :something self.something = 'Parent Default' def something(value = nil) @something = value ? value : @something ? @something : self.class.something end end class Child < Parent # inherited form Parent.something end class GrandChild < Child something "GrandChild default" end 

Results in:

 Parent.something # => "Parent Default" Parent.something = "Parent something else" # => "Parent something else" Parent.something # => "Parent something else" parent = Parent.new # => #<Parent:0x007fc593474900> parent.something # => "Parent something else" parent.something = "yet something different" # => "yet something different" parent.something # => "yet something different" parent.class.something # => "Parent something else" Child.something # => "Parent Default" child = Child.new # => #<Child:0x007fc5934241f8> child.something # => "Parent Default" GrandChild.something # => "GrandChild default" GrandChild.something("grandchild something else") # => "grandchild something else" GrandChild.something # => "grandchild something else" GrandChild.superclass.something # => "Parent Default" grandchild = GrandChild.new # => #<GrandChild:0x007fc5933e70c8> grandchild.something # => "grandchild something else" grandchild.something = "whatever" # => "whatever" GrandChild.something # => "grandchild something else" grandchild.something # => "whatever" 
0
source share

All Articles