Ruby getting the longest word of a sentence

前端 未结 7 965
时光说笑
时光说笑 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
    慢半拍i (楼主)
    2021-01-12 11:42

    Funcional Style Version

    str.split(' ').reduce { |r, w| w.length > r.length ? w : r }
    

    Another solution using max

    str.split(' ').max { |a, b| a.length <=> b.length }
    

提交回复
热议问题