如何对数组进行排序,如下所示:
[["9213533",
{:length=>"9213533",
:units=>["Meters", "Feet", "Yards"],
:frequency=>3}],
[nil,
{:length=>nil, :units=>["Feet"], :frequency=>1}],
["5951975",
{:length=>"5951975", :units=>["Yards"], :frequency=>1}],
["9100799",
{:length=>"9100799", :units=>["Feet"], :frequency=>1}]]
我想对其进行排序,以便数组数组的第一个元素为 nil 来到最后一个位置,如下所示(排序):
[["9213533",
{:length=>"9213533",
:units=>["Meters", "Feet", "Yards"],
:frequency=>3}],
["5951975",
{:length=>"5951975", :units=>["Yards"], :frequency=>1}],
["9100799",
{:length=>"9100799", :units=>["Feet"], :frequency=>1}]],
[nil,
{:length=>nil, :units=>["Feet"], :frequency=>1}]
我尝试过按方法排序(arr 是我的数组):
arr.sort_by{|a,b| b[:length] unless a.nil?}
得到了这个例外:
ArgumentError: comparison of NilClass with String failed
from (pry):395:in `sort_by