find the kth longest word in a string in ruby

To find the kth longest word in a string in Ruby, you can take the following approach:

  • Split the string into an array of words using the split method
  • Sort the array of words by their length in descending order using the sort_by method and the length attribute
  • Access the kth element of the sorted array to get the kth longest word

Here's the code that implements this logic:

main.rb
def kth_longest_word(str, k)
  # Split the string into an array of words
  words = str.split(" ")
  
  # Sort the array of words by their length in descending order
  sorted_words = words.sort_by { |word| -word.length }
  
  # Access the kth element of the sorted array to get the kth longest word
  sorted_words[k-1]
end
322 chars
11 lines

You can call this method with a string and the kth value to get the kth longest word:

main.rb
str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
kth = 3

puts kth_longest_word(str, kth) # Output: "consectetur"
197 chars
5 lines

gistlibby LogSnag