Sunday, August 18, 2013

Coderbyte: Longest Word (Ruby)

PROBLEM

Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.

SOLUTION

def LongestWord(sen)
  largest_word_data = {:length => 0, :word => ""}
  sen.gsub(/[^0-9A-Za-z ]/, '').split.each { |word| largest_word_data = {:length => word.length, :word => word} if word.length > largest_word_data[:length] }
  return largest_word_data[:word] 
end
   
print LongestWord(STDIN.gets)