Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby return statement does not work with super keyword?

Tags:

ruby

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.

like image 247
Voldemort Avatar asked May 09 '12 15:05

Voldemort


People also ask

Does Ruby automatically return?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it.

Is return necessary in Ruby?

Ruby does not require an explicit 'return' statement, but can return the last executed statement results by default.

What is the difference between calling super and calling super ()?

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.


1 Answers

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
like image 195
Cade Avatar answered Sep 23 '22 10:09

Cade