I had a project I was working on that required me to assign values to incremental variables from an array. A quick solution to the problem, using very little meta-coding is below in its most basic form. One class was my data or value class. It held the incremental variables I wanted to assign to. Here It's called, "Foo". The class that is using this data is "Bar". Just for spice, I randomized the array values to assign to the data variables. class Foo attr_accessor :i0, :i1, :i2, :i3 initialize @i0 = 0; @i1 = 0; @i2 = 0; @i3 = 0 end end class Bar attr_accessor :f def initialize @f = Foo.new @image_sort = %w{ 1 2 3 4 }.shuffle end def setup @image_sort.each_with_index do | i, idx | @f.instance_variable_set( :"@i#{idx}", i ) end puts @f.i0 puts @f.i1 puts @f.i2 puts @f.i3 end end g = Bar.new g.setup
Adventures in programming and hacking.