title: Ruby: Undefined method 'length' for nil:NilClass (NoMethodError)
body: <p>I am attempting to write a program that takes in a string and outputs the longest word in that string. Now, I know that my code looks pretty hairy but I am pretty new to the Ruby language so please just bear with me. I don't understand any of the other explanations given regarding this issue. I am not looking for the answer. All I want is for a kind human being to please explain to me why my program halts at line 16 with the problem stated in the title of this question. Please and thank you!</p>
  
  <pre class="lang-ruby prettyprint-override"><code># longest_word.rb
  # A method that takes in a string and returns the longest word
  # in the string. Assume that the string contains only
  # letters and spaces. I have used the String 'split' method to
  # aid me in my quest. Difficulty: easy.
  
  def longest_word(sentence)
    array = sentence.split(" ")
  
    idx = 0
    ordered_array = []
  
    puts(array.length)
  
    while idx &lt;= array.length
      if (array[idx].length) &lt; (array[idx + 1].length)
        short_word = array[idx]
        ordered_array.push(short_word)
        idx += 1
      elsif array[idx].length &gt; array[idx + 1].length
        long_word = array[idx]
        ordered_array.unshift(long_word)
        idx += 1
      else l_w = ordered_array[0]
        return l_w
      end
    end
  end
  
  puts("\nTests for #longest_word")
  puts(longest_word("hi hello goodbye"))
  </code></pre>