我想了解sort_by
方法。这里有一个脚本,我尝试用:在散列数组中,如何编辑特定的散列索引?
def test(x)
if x[:type] == 1
# move the hash to the first index of the array
end
end
values = [{value: "First", type: 0},{value: "Second", type: 1},{value: "1111", type: 0},{value: "2222", type: 1}]
values.sort_by! { |x| test(x) }
puts values
我怎么能明确说明我想选择的指数的指数被移动到?我希望1类型的哈希全部移到前三个索引,而且它们的顺序没有改变。
你能否解释'价值返回'多一点请?究竟使用这个值是什么? – Starkers
增加了一些更多的解释。 – tihom
了解'| x | x [:type] == 1?'完全,以及它如何遍历数组。我知道当'x [:type] == 1时,冒号左边的值是'returned'吗?'是真实的,冒号右边的值在错误时被'返回'。但我仍然不太明白这些值是如何使用的......当你说返回的值是0时,你意味着当前散列索引在数组内被设置为0? – Starkers