What's a good way to sort strings in ruby so that empty strings are at the end?

  • A+
Category:Languages

In Ruby the default sort puts empty strings first.

['', 'g', 'z', 'a', 'r', 'u', '', 'n'].sort 

Gives:

["", "", "a", "g", "n", "r", "u", "z"] 

However, it's quite common to want empty strings at the end instead.

Doing something like:

['', 'g', 'z', 'a', 'r', 'u', '', 'n'].sort { |a, b| a[0] && b[0] ?  a <=> b : a[0] ? -1 : b[0] ? 1 : 0 } 

works and gives:

["a", "g", "n", "r", "u", "z", "", ""] 

However, this isn't very readable and is not very flexible.

Is there a reasonable and clean way to get sort in Ruby to put empty strings last? Would it be better to just map to an array with no empty strings, sort, and then pad on the empty strings at the end? Are there other approaches?

 


arr = ["g", "u", "", "a", "", "r", "n", "z"]  arr.sort_by { |s| [s.empty? ? 1 : 0, s] }   #=> ["a", "g", "n", "r", "u", "z", "", ""] 

or

arr.sort_by { |s| s.empty? ? 255.chr : s }   # => ["a", "g", "n", "r", "u", "z", "", ""] 

or

empty, non_empty = arr.partition(&:empty?)   #=> [["", ""], ["g", "u", "a", "r", "n", "z"]] non_empty.sort.concat empty   #=> ["a", "g", "n", "r", "u", "z", "", ""] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: