[英]How to sort a mixed array by different elements in Ruby?
我有一個類似於這樣的數組:
a = [
[0, {:a=>"31", :b=>"21"}],
[1, {:a=>"32", :b=>"11"}],
[1, {:a=>"25", :b=>"19"}],
[0, {:a=>"12", :b=>"10"}]
]
我希望按每行的第一個元素或散列的各個元素(行中的第二個元素)對其進行排序。
按數組中的第一項排序:
> a.sort_by{|x| x.first}
=> [[0, {:a=>"31", :b=>"21"}],
[0, {:a=>"12", :b=>"10"}],
[1, {:a=>"32", :b=>"11"}],
[1, {:a=>"25", :b=>"19"}]]
按哈希中的第一項排序:
> a.sort_by{|x| x.last.first}
=> [[0, {:a=>"12", :b=>"10"}],
[1, {:a=>"25", :b=>"19"}],
[0, {:a=>"31", :b=>"21"}],
[1, {:a=>"32", :b=>"11"}]]
或者您可以按散列的給定鍵進行排序:
> sort_key = :b
> a.sort_by{|x| x.last[ sort_key ]}
=> [[0, {:a=>"12", :b=>"10"}],
[1, {:a=>"32", :b=>"11"}],
[1, {:a=>"25", :b=>"19"}],
[0, {:a=>"31", :b=>"21"}]]
如果要按第一個數組值排序,然后按哈希中的第一個條目排序,作為輔助搜索條件,答案是:
> a.sort_by{|x| [x.first, x.last.first]}
=> [[0, {:a=>"12", :b=>"10"}],
[0, {:a=>"31", :b=>"21"}],
[1, {:a=>"25", :b=>"19"}],
[1, {:a=>"32", :b=>"11"}]]
a = [
[0, {:a=>"31", :b=>"21"}],
[1, {:a=>"32", :b=>"11"}],
[1, {:a=>"25", :b=>"19"}],
[0, {:a=>"12", :b=>"10"}]
]
p a.sort_by{|el| [el.first, *el.last.values]}
輸出:
=> [[0, {:a=>"12", :b=>"10"}],
[0, {:a=>"31", :b=>"21"}],
[1, {:a=>"25", :b=>"19"}],
[1, {:a=>"32", :b=>"11"}]]
好吧,我找到了自己問題的答案。 請比較和評論。
#sort by first item of each row (number)
a.sort{|x,y| x[0] <=> y[0]}
#sort by the first item in the hash
a.sort{|x,y| x[1][:a] <=> y[1][:a]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.