Q:

Ruby: undefined method `[]=' for nil:NilClass

Sorry for my poor English. I got the error like below.
undefined method `[]=' for nil:NilClass

app/controllers/tasks_controller.rb:69:in `block in show'
app/controllers/tasks_controller.rb:67:in `each'
app/controllers/tasks_controller.rb:67:in `each_with_index'
app/controllers/tasks_controller.rb:67:in `show'

Here is the code in 'tasks_controller.rb':
@teammates_form = Array.new(@teammates.size-1){Hash.new}
@teammates.each_with_index do |t, idx|
  if t.id != current_user.id
    @teammates_form[idx]['id'] = t.id  # <--- line 69
    @teammates_form[idx]['name'] = t.name
    @teammates_form[idx]['t_id'] = @task.id
  end
end

But if I change codes like:
@teammates_form[0]['id'] = t.id
@teammates_form[0]['name'] = t.name
@teammates_form[0]['t_id'] = @task.id

It works... I don't know why I can't use index in array.
Thanks in advance for any help.

A:

#                                          ⇓⇓  ? WHY?
@teammates_form = Array.new(@teammates.size-1){Hash.new}

You yield this error on the last iteration on @teammates, since @teammates_form is 1 element shorter.

