1

I'm trying to turn a string into an array sorted first by descending length, then by descending alphabetical order among strings of similar length. That is, "x ya yz z" should return ["yz", "ya", "z", "x"]. I see that an analogous question was posed in python. What would the ruby way be?

I understand the string can be sorted by descending length with

string = 'Joe John Bill Juan Bill'

x = string.split.sort_by(&:length).reverse.uniq
Community
  • 1
  • 1
gonzalo2000
  • 628
  • 1
  • 8
  • 22

3 Answers3

4

This should work:

string.split.sort_by { |e| -e.length }.group_by(&:length).map{ |_, v| v.sort.reverse }.flatten
Maxim Pontyushenko
  • 2,983
  • 2
  • 25
  • 36
3

Just use Array#sort with the size and the string itself like this:

array = 'Joe John Bill Juan Bill'
array.split(' ').sort { |a, b| [b.size, b] <=> [a.size, a] }
#=> ["Juan", "John", "Bill", "Bill", "Joe"]
Doguita
  • 15,403
  • 3
  • 27
  • 36
1
"x ya yz z".split.sort_by{|s| [s.length, s]}.reverse
# => ["yz", "ya", "z", "x"]
sawa
  • 165,429
  • 45
  • 277
  • 381