0

ruby code

def something
  p 'hellp something'
  'hello'
end

p something + 'xx'
p '-----------'
something = something + 'xx'

The last code run error:

test01.rb:11:in <main>': undefined method+' for nil:NilClass (NoMethodError)

This is my understanding of the last code:

  1. ruby explain the code from left to right.
  2. Ruby parser see 'something' first, then it will see '=' on the right. So, it think the 'something' as a variable and its value is nil.
  3. Ruby parser will see the second 'something', but do not know this is a variable or a method. So, it looks up the same name variable or method. Then it find the nil value 'something'. " nil + 'xx' " this code run with error.

I do not know whether my understanding is correct.

3
  • 2
    please, use English on this resource. Commented Sep 8, 2016 at 9:52
  • OK, I have use English on this resource, thank you. Commented Sep 9, 2016 at 2:13
  • 1
    Yes, this is more or less what happens. Commented Jul 23, 2017 at 7:49

1 Answer 1

1

In ruby everything is a class.

The line that is messing up your code is something = something + 'xx' at this moment the compiler is going to mix up everything in the following sequence.

  1. the first something is given the nil value (from the NilClass)
  2. the second something at the right of the equal sign is no longer associated with the method something you previously defined but to the nil object that was defined at step #1.
  3. then, and this is when the error is triggered, you try to perform an operation on a nil object that is not allowed in ruby.
Sign up to request clarification or add additional context in comments.

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.