Reputation: 1893
I have the empty hash @task_data = Hash.new({task_name: '', updated_at: '', worked_by: ''})
Now I want to loop around the variable and adding the value into the hash @task_data something like below
i = 1
@tasks.each do |task|
@task_data[i][:task_name] = task.task_name
@task_data[i][:update_at] = task.updated_at.strftime("%d/%m/%Y")
if task.task_timings.present? && !task.task_timings.last.user_id.nil?
@task_data[i][:worked_by] = task.task_timings.last.user.name
else
@task_data[i][:worked_by] = ''
end
i = i+1
end
end
But when I displayed the value after the loop it's still empty.
I need something like @task_data = {1 => {task_name: '', updated_at: '', worked_by: ''}, 2 => {task_name: '', updated_at: '', worked_by: ''}, 3 => {task_name: '', updated_at: '', worked_by: ''}}
Please help me
Upvotes: 0
Views: 61
Reputation: 18454
Ruby has functional style for more readable notation (see Enumerable#map
), also you can use safe navigation operator here:
@task_data = @tasks.map do |task|
{
task_name: task.task_name,
update_at: task.updated_at.strftime("%d/%m/%Y"),
worked_by: task.task_timings.last&.user&.name || ''
}
end.each.with_index(1).to_h{|task,index| [index, task]}
Upvotes: 2
Reputation: 1
Hash[tasks.map.with_index(1) do |task, idx|
[idx, {task_name: task.task_name, updated_at: task.updated_at.strftime("%d/%m/%Y"), worked_by: task.task_timings.last.user.name}]
]
Upvotes: 0