-1

I am trying to do this test and there are bunch of solutions online and here but I first want to figure out why my solution is wrong even though it seems that it puts right results when I enter certain strings :

Here is what they are asking :

Write a method that takes in a string. Return the longest word in the string. You may assume that the string contains only letters and spaces.

You may use the String split method to aid you in your quest.

Here is my solution where I thought I could turn string into array, sort it from max length descending and then just print first element in that new string like this :

def longest_word(sentence)
  sentence = sentence.split

  sentence.sort_by! { |longest| -longest.length }

  return sentence[0]
end

That doesn't seem to work obviously since their test gives me all false..here is the test :

puts("\nTests for #longest_word")
puts("===============================================")
    puts(
      'longest_word("short longest") == "longest": ' +
      (longest_word('short longest') == 'longest').to_s
    )
    puts(
      'longest_word("one") == "one": ' +
      (longest_word('one') == 'one').to_s
    )
    puts(
      'longest_word("abc def abcde") == "abcde": ' +
      (longest_word('abc def abcde') == 'abcde').to_s
    )
puts("===============================================")

So the question is why? And can I just fix my code or the idea is all wrong and I need to do it completely different?

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
SrdjaNo1
  • 755
  • 3
  • 8
  • 18

2 Answers2

1
str = "Which word in this string is longest?"

r = /[[:alpha:]]+/
str.scan(r).max_by(&:length)
  #=> "longest"

This regular expression reads, "match one or more characters". The outer brackets constitute a character class, meaning one of the characters within the brackets must be matched.

To deal with words that are hyphenated or contain single quotes, the following is an imperfect modification1:

str = "Who said that chicken is finger-licken' good?"

r = /[[[:alpha:]]'-]+/
str.scan(r).max_by(&:length)
  #=> "finger-licken'"

This regular expression reads, "match one or more characters that are a letter, apostrophe or hyphen". The outer brackets constitute a character class, meaning one of the characters within the brackets must be matched.

1 I've successfully used "finger-licken'" in scrabble.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
-1

I'd write it something like:

str = "Write a method that takes in a string"
str.split.sort_by(&:length).last # => "string"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303