Skip to content

Instantly share code, notes, and snippets.

@polyglotdev
Created September 22, 2021 18:37
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 polyglotdev/4800f1c8f0252eab5fa4905432b1c380 to your computer and use it in GitHub Desktop.
Save polyglotdev/4800f1c8f0252eab5fa4905432b1c380 to your computer and use it in GitHub Desktop.
longest word
# frozen_string_literal: true
def longest_word(sentence)
split_sentence = sentence.split
my_longest_word = split_sentence.max_by { |word| word.size }
same_length_words = split_sentence.select { |word| word.size == my_longest_word.size }
if same_length_words.empty?
my_longest_word
else
same_length_words.last
end
end
ruby_love = 'Ruby is my favorite language'
bobby_is_weird = 'Bobby loves big scary kangaroos'
p longest_word(ruby_love)
p longest_word(bobby_is_weird)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment