Ken*_*Ken 1 ruby arrays sorting
给出一个类似的数组
x = [1, 3, 5, -1, -3, -5]
Run Code Online (Sandbox Code Playgroud)
如果我们使用该命令
x.sort {|i| i}
Run Code Online (Sandbox Code Playgroud)
我们得到了
x = [-1, -3, -5, 1, 3, 5]
Run Code Online (Sandbox Code Playgroud)
在给定我们的数组的情况下,有没有办法让它以正负的升序/降序返回?例如
x = [-5, -3, -1, 1, 3, 5] or [5, 3, 1, -1, -3, -5]
Run Code Online (Sandbox Code Playgroud)
编辑:
似乎x.sort会解决这个问题,但是如果有一个更复杂的问题,我想根据哈希中给出的值从我的数组中排序,例如
x = [{:i=>1}, {:i=>2}, {:i=>3}, {:i=>4}, {:i=>5}]
y = {3=>10, 4=>-1, 2=>-2, 5=>-3, 1=>-4}
Run Code Online (Sandbox Code Playgroud)
我希望能够根据y中的值对x进行排序,以便我的结果是
x = [{:i=>3}, {:i=>4}, {:i=>2}, {:i=>5}, {:i=>1}]
Run Code Online (Sandbox Code Playgroud)
x = [1, 3, 5, -1, -3, -5]
x.sort # => [-5, -3, -1, 1, 3, 5]
x.sort {|a,b| a <=> b} # => [-5, -3, -1, 1, 3, 5]
x.sort {|a,b| b <=> a} # => [5, 3, 1, -1, -3, -5]
Run Code Online (Sandbox Code Playgroud)
由于Array#sort方法预期返回值,您的示例会产生意外结果.基本上,当你只返回第一个参数时(当需要两个时),解释器只查看元素的符号( - /0/+)并使用它来进行排序.因此,根据底层排序算法,当它产生从数组到块的对时,它只查看第一个元素的符号,所以类似于:
compare(1, 3) # => 1 (wrong, should be -1 since 1 < 3)
compare(1, 5) # => 1 (wrong, should be -1 since 1 < 5)
compare(1, -1) # => 1 (right, by complete accident)
Run Code Online (Sandbox Code Playgroud)
[编辑]根据您更新的问题,尝试使用以下排序比较器块:
x.sort! {|a,b| y[b[:i]] <=> y[a[:i]]}
x # => [{:i=>3}, {:i=>4}, {:i=>2}, {:i=>5}, {:i=>1}]
Run Code Online (Sandbox Code Playgroud)
哪些读取 - x通过比较每个元素对对数组进行排序,a并b通过:i在哈希中查找它们的属性y并按降序比较这些值.