So I had this bug where I had a method:
def returnArr
[2,3,4]
end
And I did this:
returnArr = returnArr.first
returned an error stating that nilClass doesn’t have a method ‘first’
Moreover, after doing that line of code, and follow it up with this:
returnArr = returnArr().first
worked completely fine, and returnArr is now different from returnArr(). What is going on here?
When you have this line
Ruby sees (and executes) this:
Before assigning value to a variable, this variable is initialized to
nil. So, in this case, your local variable shadows your method. Without hints from your side, ruby can’t determine that actually you wanted to call the method. When you provide parentheses, ruby understands that local variable can’t have them and calls the method.Don’t ever do this again. Especially in a real app.