You could define instance variables dynamically :
5.times do |i|
instance_variable_set(:"@reader#{i}", "library_name#{i}")
instance_variable_set(:"@book#{i}", "book_title#{i}")
end
puts @reader1
puts @book1
puts @book4
# => library_name1
# book_title1
# book_title4
Another possibility would be to use method_missing to fake local variables, while using instance variables as cache :
def create_variable_or_use_cache(name, &block)
name = "@#{name}"
instance_variable_get(name) || instance_variable_set(name, block.yield)
end
def method_missing(sym,*p)
if sym=~/^reader(\d+)$/ then
create_variable_or_use_cache(sym){ "Create reader#{$1} here" }
elsif sym=~/^book(\d+)$/ then
create_variable_or_use_cache(sym){ "Create book#{$1} here" }
else
super
end
end
puts reader1
puts reader1
puts book3
wrong_method
# =>
# Create reader1 here
# Create reader1 here
# Create book3 here
# binding.rb:13:in `method_missing': undefined local variable or method `wrong_method' for main:Object (NameError)
It's an interesting Ruby exercise, I'm not sure you should use it though.
eval.)