Skip to content

Instantly share code, notes, and snippets.

@erochest
Created September 19, 2011 16:13
Show Gist options
  • Save erochest/1226854 to your computer and use it in GitHub Desktop.
Save erochest/1226854 to your computer and use it in GitHub Desktop.
This indexes the words in a string by length.
# The input.
INPUT = 'The quick brown fox jumped over the lazy dogs. ABCDEF'
# Create a hash that returns an empty Array for missing item accesses.
len_index = Hash.new do |hash, key|
hash[key] = []
end
# Split the input and store each word in the hash, keyed by the length of the
# word.
INPUT.split(' ').each do |word|
len_index[word.length] << word
end
# Get the maximum key length.
longest_len = len_index.keys.max
puts "The longest is #{len_index[longest_len].inspect} (#{longest_len})."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment