Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Ruby Longest Word
    Why doesn't this code produce the correct output for the Ruby longest word challenge? Why does it always give me the first object in the array? In other words, What is this code doing and how do I make it do what i want it to?
    def LongestWord(sen)
      my_array = sen.split
      my_array.each { |a_word| return a_word if a_word == my_array.max_by{sen.length}} 
      return my_array
    end
    
    sayheykid posted this question on 10/14/15 | ruby, longest, word
    Answers
  • +
  • 1
  • -
  • def LongestWord (sen) return sorted[0];var' [answer]; if [longest word] not '=' (string) sen.split.max_by { la_word | a_word.leghth} end
  • +
  • 1
  • -
  • Additionally you don't need the last line
    return my_array
    
    This will never get evaluated in this case, and all you would be doing is returning the split array you created. In ruby if nothing is returned implicitly, the last line before the end of your method will be returned.
  • +
  • 0
  • -
  • I don't think your understanding how the max_by method works. Go to the Ruby Docs and check up on it You are iterating over your my_array and returning a_word if a_word == my_array.max_by{sen.length} If you run that last snippet my_array.max_by{sen.length} you'll see that it gives you the first word in your array, therefore your condition statement evaluates to true and the word is returned, thus breaking you out of the method. Your .max_by{sen.length} just doesn't make any sense in the way you are trying to implement the block.
    def LongestWord(sen)
      sen.split.max_by {|a_word| a_word.length}
    end
    
  • +
  • 0
  • -
  • I believe it is always returning the first object because the return in your block is returning to the yield of the 'each' call and not the the function. If you take out the last return in the function I think it would return the longest word implicetly since it would be the last expression of the function
    Log in to write an answer.