0

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

2 Answers 2

2

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]}
Sign up to request clarification or add additional context in comments.

2 Comments

.each.with_index(1).to_h.invert has the chance to reduce the output count if two tasks are considered the same, since they will be used as key first. You could change this to .each.with_index(1).to_h { |task, i| [i, task] } to resolve this. Example tasks = [{a: 1}, {a: 1}] would produce {2 => {a: 1}} with the current solution.
Also each.with_index(1).with_object({}) do |(task,idx),obj| would make this a bit cleaner too then the loop would just be obj[idx] = { task_name: task.task_name, update_at: task.updated_at.strftime("%d/%m/%Y"), worked_by: task.task_timings.last&.user&.name || '' }
0
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}]
]

1 Comment

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.