我必须重新排序Destinations的哈希值,所以我想在这样的数组中创建一个数组:
@orderedDestinations = Array.new
@destinations.each do |destination|
if (destination.position != nil)
@orderedDestinations[destination.position][destination.id] = destination
end
end
我收到了这个错误:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]=
我做错了什么?
答案 0 :(得分:3)
如果您想按@destinations
排序Destination#position
,您应该这样做:
@orderedDestinations = @destinations.sort_by(&:position)
http://ruby-doc.org/core-1.9.2/Enumerable.html#method-i-sort_by
完成交易。
答案 1 :(得分:2)
@orderedDestinations[destination.position] is nil so:
@orderedDestinations[destination.position][destination.id] really is:
-> nil[destination.id]
答案 2 :(得分:1)
在Ruby中,除非明确初始化为某些内容,否则大多数内容都是nil
。例如,如果新数组的所有元素不存在或之前未分配,则它们默认为此。像这样:
test = [ 1, 2 ]
# => [1,2]
test[1]
# => 2
test[2]
# => nil
您可能想要做的是根据需要初始化数组的第二级。你可以采用这样的模式:
@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
为您的第二级条目选择数组[ ]
或哈希{ }
取决于您在其中存储的数据类型。散列表可以轻松处理任意标识符,其中数组最适合通常从零开始或接近零开始的顺序数。如果初始化数组的元素X,则该数组将自动变为大小X + 1。
答案 3 :(得分:0)
是, 谢谢。解决方案是添加以下行:
@orderedDestinations[destination.position] ||= {}
所以完整的代码是:
@orderedDestinations = Array.new
@destinations.each do |destination|
if (destination.position != nil)
@orderedDestinations[destination.position] ||= {}
@orderedDestinations[destination.position][destination.id] = destination
end
end
谢谢。