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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.