0

I'm trying work something out in ruby.

I have the months of the year in an array like this.

months = ['april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'january', 'february', 'march']

I have then defined a class called Month, which looks like this...

class Month
  attr_accessor :name, :accounts, :income
  def initialize(name, accounts, income)  
    # Instance variables  
    @name = name  
    @accounts = accounts
    @income = income  
  end  
end

Now I am trying to create 12 instances of the Month class with an iterator like this

months.each do |month|
  xxx = Month.new(month, 50, 1000)
end

The bit I am struggling with is the xxx. I want this to be the name of the month, so I end up being able to do april.accounts, may.income etc. No matter what I try I cannot seem to figure it out?

Can anyone help?

Gareth Burrows
  • 1,142
  • 10
  • 22

1 Answers1

2

Use this instance_variable_set method.

months.each do |month|
  instance_variable_set :"@#{month}", Month.new(month, 50, 1000)
end
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317