views:

43

answers:

2

I have a to-do list with 5 tasks that are stored on the same record.

Todo.task_one, Todo.task_two, etc.

What I would like to do is be able to loop through the fields like this

total_tasks = ["one", "two", "three", "four", "five"]
for tasks in total_tasks
Todo.task_#{tasks} = "text here"
end

However, this doesn't work unless I use eval "Todo.task_#{tasks} = 'text here'" which I know isn't safe. Even using eval isn't really the solution, because I need to do this in the view using erb, so I'm kind of stuck.

+6  A: 

Ruby is full of metaprogramming utilities. One such utility is Object#send.

["one", "two", "three", "four", "five"].each do |task|
  Task.send("task_#{task}=", "text here")
end

Another option is to not give the tasks human friendly method names.

5.times do |i|
  Task.tasks[i] = "foo"
end
August Lilleaas
Worked great! Thanks. Also, it can be used in reverse: task_text = Task.send("task_#{task_number}")
Canuk
A: 

What you're looking for is the send method that all Ruby objects have. It allows you to 'send' a message (which is what calling a method really is anyways) with a string.

Example:

Todo.send("task_#{tasks}")

It will return whatever your task methods return.

Ben