I am currently self teaching Ruby and am practicing methods. So, I just don't seem to understand why my console continuously prints out a error message after the proper conditional is printed. Any explanation would be appreciated!
def test(tester)
if tester
puts "yes";
else
puts "error";
end
end
#call function
test(:tester).("hello world");
Output:
yes
main.rb:10:in `<main>': undefined method `call' for nil:NilClass (NoMethodError)
Why am I getting this error??
CodePudding user response:
foo.(bar)
is syntactic sugar for foo.call(bar)
. So, test(:tester).("hello world")
is syntactic sugar for test(:tester).call("hello world")
.
However, test
returns nil
, so you are calling nil.("hello world")
which is the same as nil.call("hello world")
, and if you look at the documentation of NilClass
, you can easily see that it does not have a method named call
. (NilClass
inherits from Object
which in turn inherits from Kernel
and BasicObject
, so theoretically, the method could be defined there, but as you can easily check yourself, it isn't.)
Since you are calling a method that does not exist, you get a NoMethodError
.