Created
October 30, 2014 20:14
-
-
Save shortdiv/9f33786f2f8b970b4e70 to your computer and use it in GitHub Desktop.
The most complicated possible way of sorting a sentence by word length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sort_string(string) | |
word_hash = {} | |
new_word = "" | |
string.split(" ").each do |word| | |
word_hash[word] = word.length | |
end | |
numbers = word_hash.values.sort | |
first_num = numbers.first | |
new_word << word_hash.key(first_num) | |
numbers.delete(first_num) | |
numbers.each do |val| | |
new_word << " " + word_hash.key(val) | |
end | |
new_word | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def sort_string(string)
string.split(' ').sort{|x, y| x.length <=> y.length}.join(' ')
end
Better Solution ^