class Parent
def test
return
end
end
class Child < Parent
def test
super
p "HOW IS THIS POSSIBLE?!"
end
end
c = Child.new
c.test
I though that, since the test
method from the Parent
class immediately uses the return statement, it should not be possible to print the line of the Child
class. But it is indeed printed. Why is that?
Ruby 1.8.7, Mac OSX.
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it.
Ruby does not require an explicit 'return' statement, but can return the last executed statement results by default.
When you call super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method with the same name as where you called super from, along with the arguments that were passed to that method. On the other hand, when called with super() , it sends no arguments to the parent.
Another way to think of the call to super
in this context is if it were any other method:
class Parent
def foo
return
end
end
class Child < Parent
def test
foo
p "THIS SEEMS TOTALLY REASONABLE!"
end
end
c = Child.new
c.test
# => "THIS SEEMS TOTALLY REASONABLE!"
If you really wanted to prevent the call to p
, you need to use the return value from super
in a conditional:
class Parent
def test
return
end
end
class Child < Parent
def test
p "THIS SEEMS TOTALLY REASONABLE!" if super
end
end
c = Child.new
c.test
# => nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With