[英]rails sort_by string with empty string latest
foot = [{val: "left"}, {val: "right"}, {val: nil}]
foot.sort_by{ |f| f[:val].to_s }
=> [{:val=>nil}, {:val=>"left"},{:val=>"right"}]
How do I sort such array descеnded with nil-elements at the end of the list? 如何对列表末尾用nil-elements表示的数组进行排序? => left, right, nil =>左,右,无
The most obvious thing is to separate array into 2 parts: with nil values, and the other: 最明显的是将数组分为两部分:使用nil值,另一部分:
foot = [{val: "left"}, {val: "right"}, {val: nil}]
nil_array, str_array = foot.partition { |h| h[:val].nil? }
str_array.sort_by{ |f| f[:val].to_s }.concat(nil_array)
If it were numbers, I would also suggested something like: 如果是数字,我还建议如下:
foot.sort_by { |f| f[:val] ? f[:val] : Float::INFINITY }
You can use sort
to compare pairs of values and handle nil
values explicity in the comparisons. 您可以使用sort
比较值对并在比较中显式处理nil
值。
foot = [{val: "left"}, {val: "right"}, {val: nil}]
foot.sort{ |a,b| a[:val].nil? ? 1 : ( b[:val].nil? ? -1 : a[:val] <=> b[:val]) }
=> [{:val=>"left"},{:val=>"right"},{:val=>nil}]
较短的一个:
foot.sort_by { |a| [a[:val] ? '' : ' ', a[:val].to_s] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.