Kyle Sletten
Kyle Sletten

Reputation: 5413

Calling Super Methods in Ruby

I am trying to define some classes in Ruby that have an inheritance hierarchy, but I want to use one of the methods in the base class in the derived class. The twist is that I don't want to call the exact method I'm in, I want to call a different one. The following doesn't work, but it's what I want to do (basically).

class A
    def foo
        puts 'A::foo'
    end
end

class B < A
    def foo
        puts 'B::foo'
    end
    def bar
        super.foo
    end
end

Upvotes: 1

Views: 904

Answers (2)

G. Allen Morris III
G. Allen Morris III

Reputation: 1042

A more general solution.

class A
  def foo
    puts "A::foo"
  end
end

class B < A
  def foo
    puts "B::foo"
  end
  def bar
    # slightly oddly ancestors includes the class itself
    puts self.class.ancestors[1].instance_method(:foo).bind(self).call
  end
end

B.new.foo # => B::foo
B.new.bar # => A::foo

Upvotes: 0

sawa
sawa

Reputation: 168121

Probably, this is what you want?

class A
  def foo
    puts 'A::foo'
  end
end

class B < A
  alias bar :foo
  def foo
    puts 'B::foo'
  end
end

B.new.foo # => B::foo
B.new.bar # => A::foo

Upvotes: 5

Related Questions