Skip to content

Instantly share code, notes, and snippets.

@shortdiv
Created October 30, 2014 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shortdiv/9f33786f2f8b970b4e70 to your computer and use it in GitHub Desktop.
Save shortdiv/9f33786f2f8b970b4e70 to your computer and use it in GitHub Desktop.
The most complicated possible way of sorting a sentence by word length
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
@shortdiv
Copy link
Author

def sort_string(string)
string.split(' ').sort{|x, y| x.length <=> y.length}.join(' ')
end

Better Solution ^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment