1

I have this code

def longest_word(sentence)
  long_word = ""
  sentence.split(" ").sort_by {|x| x.length}
  long_word = sentence.pop

  return long_word
end

p longest_word("hello dogs are fast")

And I get the error that the method 'pop' is undefined when I try running it. Does this have something to do with gemfiles? I thought I set that stuff up already.

3 Answers 3

2

You are calling array method pop on a string sentence, not a received from split array of strings.

By the way, your code can be simplified:

def longest_word(sentence)
  sentence.split(' ').sort_by(&:length).pop
end

p longest_word("hello dogs are fast")
#=> "hello"

Demonstration

You can also use max_by:

sentence.split(" ").max_by(&:length)

Demonstration

Sign up to request clarification or add additional context in comments.

Comments

0

You're calling pop on sentence, which is a String.

You probably want this:

long_word = sentence.split(" ").sort_by {|x| x.length}.pop

Comments

0

split and sort_by do not change the variable in any way, they return a new value. Thus, if you don't assign this to something, sentence remains a String, "hello dogs are fast", and strings don't have #pop.

sentence = sentence.split(" ").sort_by {|x| x.length}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.