Ruby getting the longest word of a sentence

前端 未结 7 966
时光说笑
时光说笑 2021-01-12 11:27

I\'m trying to create method named longest_word that takes a sentence as an argument and The function will return the longest word of the sentence.

My c

7条回答
  •  猫巷女王i
    2021-01-12 12:06

    sort_by! and reverse!

    def longest_word(sentence)
      longw = sentence.split(" ")
      longw.sort_by!(&:length).reverse!
      p longw[0]
    end
    
    longest_word("once upon a time long ago a very longword")
    

提交回复
热议问题