find the shortest word in a string in ruby

Here's one way to find the shortest word in a string in Ruby:

main.rb
def shortest_word(string)
  words = string.split(" ")
  shortest = words.first
  words.each do |word|
    shortest = word if word.length < shortest.length
  end
  shortest
end
176 chars
9 lines

This code defines a method shortest_word that takes a string as input. It first splits the string into an array of words using the split method, with the separator being a space. It then initializes the shortest variable as the first word in the array.

The method then iterates over each word in the array using each and compares the length of the current word with the length of shortest. If word is shorter than shortest, it becomes the new value of shortest.

Finally, the method returns shortest, which is the shortest word in the input string.

Example usage:

main.rb
puts shortest_word("The quick brown fox jumps over the lazy dog") #=> "The"
puts shortest_word("supercalifragilisticexpialidocious") #=> "a"
141 chars
3 lines

gistlibby LogSnag