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?
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:
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.