Cherry pick from 2-1-stable fix for "undefined method `each_with_index' for nil:NilClass" bug