2

I am wondering if there is an elegant way to create variables using a loop in ruby?

Say I want to put this in some sort of loop

def workhours
  @monday = blah
  @tuesday = brah
  @wednesday = bro
  @thursday = blap
  @friday = blagh
end

What I want to be able to do

def workhour_ideally
  days = [ "monday", "tuesday", "wednesday", "thursday", "friday" ]

  days.each do |smack|
    @"smack" = whatever
  end
end

Is this possible with ruby?

Jason Kim
  • 18,102
  • 13
  • 66
  • 105

2 Answers2

5

Yes it's possible with Rails. No you shouldn't do it. If I had to guess, I'd say this is a PHPism of some kind.

What's better is to use a Hash:

@days = {
  :monday => blah,
  :tuesday => brah,
  # ...
  :friday => blagh
}

Then you can iterate over these as you wish. Referencing one of them is only slightly more typing: @days[:monday] instead of @monday.

Using a proper data structure allows you to manipulate it, iterate over it, and offers all kinds of opportunities to test it thoroughly.

tadman
  • 208,517
  • 23
  • 234
  • 262
2

Yes, it's possible. I think it's called instance_variable_set and it'd be safer doing that than using the evil eval .

But use a hash instead if practical.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338