5

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?

1
  • you meant "module A" ... not method A ... ? And returning '3' in case of a==2 is probably not a good case, because that's the same result as the original b(a) method -- this way you won't see the difference Commented Oct 19, 2011 at 22:55

2 Answers 2

10

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" 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, didn't know that worked with modules. Thought it was only for super classes.
You don't even need to pass (a) to super. Just super without any arguments (but no empty parentheses) passes all arguments and any block to the superclass method.
@vodnik, modules are inserted into the inheritance hierarchy when you call include, so generally speaking, they behave like superclasses when used as mixins.
@d11wtq Thanks for the note on parentheses, guess this would come down to preference, for the sake of clarity I'm gonna leave them in.
3
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.