Ruby getting the longest word of a sentence

前端 未结 7 823
时光说笑
时光说笑 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条回答
  • 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 }
    
    0 讨论(0)
  • 2021-01-12 11:48
    def longest_word(sentence)
      longest_word = ""
      words = sentence.split(" ")
      words.each do |word|
        longest_word = word unless word.length < longest_word.length
      end
      longest_word
    end
    

    That's a simple way to approach it. You could also strip the punctuation using a gsub method.

    0 讨论(0)
  • 2021-01-12 11:49

    It depends on how you want to split the string. If you are happy with using a single space, than this works:

    def longest(source)
      arr = source.split(" ")
      arr.sort! { |a, b| b.length <=> a.length }
      arr[0]
    end
    

    Otherwise, use a regular expression to catch whitespace and puntuaction.

    0 讨论(0)
  • 2021-01-12 11:52

    If you truly want to do it in the Ruby way it would be:

    def longest(sentence)
    
         sentence.split(' ').sort! { |a, b| b.length <=> a.length }[0]
    
    end
    
    0 讨论(0)
  • 2021-01-12 12:05

    Using regexp will allow you to take into consideration punctuation marks.

    s = "lorem ipsum, loremmm ipsummm? loremm ipsumm...."
    

    first longest word:

    s.split(/[^\w]+/).max_by(&:length)
    # => "loremmm"
    # or using scan
    s.scan(/\b\w+\b/).max_by(&:length)
    # => "loremmm"
    

    Also you may be interested in getting all longest words:

    s.scan(/\b\w+\b/).group_by(&:length).sort.last.last
    # => ["loremmm", "ipsummm"] 
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题