Brandon Hill Brandon Hill - 3 months ago 10
Ruby Question

Ruby Error with .length method

I am running into an error with my code and I am not sure why. I am trying to create a function that returns the longest word in a string. The only built-in Ruby method I can use is .split. My code is below and the error I receive is below that. Any help with figuring this out would be appreciated.

Thanks in advance.

def longest_word(sentence)
sentence1 = sentence.split
longest_word = ""

for i in 0...sentence1.length
if i.length > longest_word.length
longest_word = i
end
end
return longest_word
end

longest_word("one three")


Error below:

undefined method `length' for 0:Fixnum
(repl):15:in `block in longest_word'
(repl):14:in `times'
(repl):14:in `longest_word'
(repl):29:in `<main>'

Answer

The issue is that you're iterating through the integers 0, 1, 2 when you pass "one three" as your argument.

Unfortunately, you can't call the length method directly on the integer/fixnum i. Instead, you want to call it on the element at the index i of the array sentence1 if that makes sense.

Something like this should work for you:

def longest_word(sentence)
  sentence1 = sentence.split
  longest_word = ""

  for i in 0...(sentence1.length - 1)
    if sentence1[i].length > longest_word.length 
      longest_word = sentence1[i]
    end 
  end
  return longest_word
end

Or, better yet

def longest_word(sentence)
  sentence.split.max_by(&:length)
end

(Stolen from http://stackoverflow.com/a/21977468/716039)

Comments