davorb
davorb

Reputation: 660

Method overriding in Ruby

I have code that looks like this:

module A
    def b(a)
      a+1
    end
end
class B
   include A
end

I would like to write a method in the class B that looks sort of like this

class B
   def b(a)
      if a==2     # are you sure? same result as the old method
         3
      else
         A.b(a)
      end
   end
end

How do I go about doing this in Ruby?

Upvotes: 4

Views: 13351

Answers (2)

Tilo
Tilo

Reputation: 33732

class B
  alias old_b b  # one way to memorize the old method b , using super below is also possible

  def b(a)
    if a==2
        '3'     # returning a string here, so you can see that it works
    else
      old_b(a)   # or call super here
    end
  end
end



ruby-1.9.2-p0 >   x = B.new
 => #<B:0x00000001029c88> 
ruby-1.9.2-p0 > 
ruby-1.9.2-p0 >   x.b(1) 
 => 2 
ruby-1.9.2-p0 > x.b(2)
 => "3"
ruby-1.9.2-p0 > x.b(3)
 => 4 

Upvotes: 3

connec
connec

Reputation: 7421

You want the super function, which invokes the 'previous' definition of the function:

module A
  def b(a)
    p 'A.b'
  end
end

class B
  include A

  def b(a)
    if a == 2
      p 'B.b'
    else
      super(a) # Or even just `super`
    end
  end
end

b = B.new
b.b(2) # "B.b"
b.b(5) # "A.b"

Upvotes: 9

Related Questions