 # Sort_by ['-100', 'dog', '-1000','cat']?

trying to solve this puzzle, but I do not know how.

given some array of strings with numbers and words , how to sort it, so I could put in a given order by digit and word length?
Thanks.

To sort an array items by their word length alone, you would do:

``````['-100', 'dog', '-1000', 'cat'].sort_by { |x| x.length }    # => ["dog", "cat", "-100", "-1000"]

# Or #

['-100', 'dog', '-1000', 'cat'].sort_by(&:length)    # => ["dog", "cat", "-100", "-1000"]
``````

To sort them by character alone, you can do this:

``````['-100', 'dog', '-1000', 'cat'].sort    # => ["-100", "-1000", "cat", "dog"]
``````

To sort them by digit first:

``````['-100', 'dog', '-1000', '10', 'cat'].sort_by { |x|
x.to_i.to_s == x ? -1 : 1
}    # => ["-100", "-1000", "10", "dog", "cat"]
``````

To sort them with digit and length combined, where digits comes first and then the strings:

``````['-100', 'dog', '-1000', '10', 'cat', 'capybara', 'mouse'].sort_by { |x|
x.to_i.to_s == x ? -1 : x.length
}    # => ["-100", "-1000", "10", "dog", "cat", "mouse", "capybara"]
``````

To sort them with the length of the digits where digits come first and then sort them the length of strings:

``````['-100', 'dog', '1000000', '-1000', '10', 'cat', 'capybara', 'mouse'].sort_by { |x|
x.to_i.to_s == x ? -x.length : x.length
}    # => ["1000000", "-1000", "-100", "10", "dog", "cat", "mouse", "capybara"]
``````

To sort the array with integers, and then sort with characters:

``````['-100', 'dog', '1000000', '-1000', '10', 'cat', 'capybara', 'mouse'].partition { |x|
x.to_i.to_s == x
}.each(&:sort!).flatten    # => ["-100", "-1000", "10", "1000000", "capybara", "cat", "dog", "mouse"]
``````
1 Like

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.