Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling another method in super class in ruby

Tags:

ruby

People also ask

Can a superclass call the methods of a subclass?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

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.

Can I access the sub class methods using a super class object?

Does a superclass have access to the members of a subclass? Does a subclass have access to the members of a superclass? No, a superclass has no knowledge of its subclasses.

What is super () in Ruby?

What does the super keyword do in Ruby? It calls a method on the parent class with the same name as the method that calls super .


class B < A

  alias :super_a :a

  def a
    b()
  end
  def b
    super_a()
  end
end  

There's no nice way to do it, but you can do A.instance_method(:a).bind(self).call, which will work, but is ugly.

You could even define your own method in Object to act like super in java:

class SuperProxy
  def initialize(obj)
    @obj = obj
  end

  def method_missing(meth, *args, &blk)
    @obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk)
  end
end

class Object
  private
  def sup
    SuperProxy.new(self)
  end
end

class A
  def a
    puts "In A#a"
  end
end

class B<A
  def a
  end

  def b
    sup.a
  end
end
B.new.b # Prints in A#a

If you don't explicitly need to call A#a from B#b, but rather need to call A#a from B#a, which is effectively what you're doing by way of B#b (unless you're example isn't complete enough to demonstrate why you're calling from B#b, you can just call super from within B#a, just like is sometimes done in initialize methods. I know this is kind of obvious, I just wanted to clarify for any Ruby new-comers that you don't have to alias (specifically this is sometimes called an "around alias") in every case.

class A
  def a
    # do stuff for A
  end
end

class B < A
  def a
    # do some stuff specific to B
    super
    # or use super() if you don't want super to pass on any args that method a might have had
    # super/super() can also be called first
    # it should be noted that some design patterns call for avoiding this construct
    # as it creates a tight coupling between the classes.  If you control both
    # classes, it's not as big a deal, but if the superclass is outside your control
    # it could change, w/o you knowing.  This is pretty much composition vs inheritance
  end
end