how to set ruby instance names in iteration -
this question has answer here:
- how dynamically create local variable? 4 answers
i'm trying work out in ruby.
i have months of year in array this.
months = ['april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'january', 'february', 'march']
i have defined class called month, looks this...
class month attr_accessor :name, :accounts, :income def initialize(name, accounts, income) # instance variables @name = name @accounts = accounts @income = income end end
now trying create 12 instances of month class iterator this
months.each |month| xxx = month.new(month, 50, 1000) end
the bit struggling xxx. want name of month, end being able april.accounts, may.income etc. no matter try cannot seem figure out?
can help?
use instance_variable_set
method.
months.each |month| instance_variable_set :"@#{month}", month.new(month, 50, 1000) end
Comments
Post a Comment