0

假设我有以下哈希数组:

arr = [{:name=>"foo", :value=>20},
       {:name=>"bar", :value=>25}, 
       {:name=>"baz", :value=>30}] 

我目前正在按value如下方式排序:

arr.sort{|a,b| b[:value] <=> a[:value] }

是否可以在排序后将元素(即其中的元素name == 'bar')移动到堆栈顶部而不链接另一种方法?理想情况下,这只是排序块中的更多内容。

4

3 回答 3

2

快速解决方案(我认为可以重构)

arr.sort{|a,b| a[:name] == 'bar' ? -1 : b[:name] == 'bar' ? 1 : b[:value] <=> a[:value] }
# => [{:name=>"bar", :value=>25}, {:name=>"baz", :value=>30}, {:name=>"foo", :value=>20}] 
于 2012-12-02T13:33:36.607 回答
1

首先,您应该对Enumerable#sort_by使用不那么冗长(并且更有效)的Schwartzian 变换

arr.sort_by { |h| -h[:value]] }

现在,利用数组定义的字典顺序,您要求的内容可以写成:

arr.sort_by { |h| [h[:name] == "bar" ? 0 : 1, -h[:value]] }
于 2012-12-02T14:14:51.213 回答
0
arr.sort do |a,b|
  if a[:name] == "bar" && b[:name] != "bar"
    # a is bar but b is not, put a to the top, i.e. a is smaller than b
    -1
  elsif a[:name] != "bar" && b[:name] == "bar"
    # a is not bar but b is, put b to the top, i.e. a is bigger than b
    1
  else
    # both a and b are "bar", or bot are not "bar", than we can sort them normally
    a[:value] <=> b[:value]
  end
end

一个肮脏的解决方案,思考如何写得更好......

于 2012-12-02T13:36:10.293 回答