In Ruby, most things are nil unless explicitly initialized as something. All elements of a new array, for instance, are this by default if they don't exist or haven't been assigned to previously. Like this:
test = [ 1, 2 ]
# => [1,2]
test[1]
# => 2
test[2]
# => nil
What you probably want to do is initialize the second level of the array as required. You can employ a pattern like this:
@orderedDestinations = [ ] # Empty array
@destinations.each do |destination|
if (destination.position)
# If this element of the array has not been initialized,
# populate it with a new empty array.
destination_set = @orderedDestinations[destination.position] ||= [ ]
# Put something in this second-level array spot
destination_set[destination.id] = destination
end
end
The choice of Array [ ] or Hash { } for your second level entry depends on the kind of data you're storing in it. Hash tables handle arbitrary identifiers easily, where an Array works best with sequential numbers typically starting at or near zero. If you initialize element X of an array, that array becomes size X+1 automatically.
#nil?predicate instead of comparing objects withnil;)if destination.position