Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby getting the longest word of a sentence

Tags:

ruby

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 code is:

def longest_word(str)
  words = str.split(' ')
  longest_str = []
  return longest_str.max
end
like image 969
user3344741 Avatar asked Feb 24 '14 01:02

user3344741


4 Answers

The shortest way is to use Enumerable's max_by:

def longest(string)
  string.split(" ").max_by(&:length)
end
like image 124
CDub Avatar answered Nov 29 '22 02:11

CDub


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"] 
like image 32
trushkevich Avatar answered Nov 29 '22 00:11

trushkevich


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.

like image 31
tompave Avatar answered Nov 29 '22 01:11

tompave


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.

like image 45
Justus Eapen Avatar answered Nov 29 '22 01:11

Justus Eapen