Passing a method block to a parent class

E

Eric Anderson

If I have

**** CODE ****

class A
def method1( argument )
yield( argument )
end
end

class B < A
def method1( argument )
puts argument
super.method1( argument )
end
end

obj = B.new
obj.method1( 'foo' ) { |arg| puts arg + 'bar' }

**** CODE ****

How do I change this to allow class A to get the block. Bascially I
want to override a method to do some pre-processing, but call the
superclass to actually implement the method. The superclass method
uses a block so how do I pass that block to the superclass?

Thanks,

Eric
 
M

Mark J. Reed

If I have

**** CODE ****

class A
def method1( argument )
yield( argument )
end
end

class B < A
def method1( argument )
puts argument
super.method1( argument )
end
end

obj = B.new
obj.method1( 'foo' ) { |arg| puts arg + 'bar' }

**** CODE ****

How do I change this to allow class A to get the block. Bascially I
To pass blocks around you have to use proc arguments.

If you declare a method thus:

def method2 (argument, &block)
end

Then any block associated with a call to the method will be turned into
a Proc object and assigned to the &-marked parameter (which must be last
in the list). Like *, this works both ways; if you pass a Proc as the
last parameter of a method call and put a & in front of it, the called
method sees it as a block.

So this should do what you want:

class B < A
def method1( argument, &block )
puts argument
super.method1( argument, &block )
end
end

-Mark
 
D

daz

Eric Anderson said:
**** CODE ****

class A
def method1( argument )
yield( argument )
end
end

class B < A
def method1( argument )
puts argument
super.method1( argument )

super # <----------------###
end
end

obj = B.new
obj.method1( 'foo' ) { |arg| puts arg + 'bar' }

**** CODE ****

Thanks,

Eric

Add parameters to super only if you want to
override its default behaviour of passing
all original parameters on.

#-> foo
#-> foobar


daz
 
C

Christoph

def method1( argument )
puts argument
super.method1( argument )
end
end


The above is equivalent to

---
class B < A
def method1( argument )
puts argument
super(argument).method1( argument )
end
end
---

Just write this as

---
class B < A
def method1( argument )
puts argument
super
end
end
---

and things will work as you probably intended.
B.t.w this also works if you modify the argument
supplied to super, as in

---
class A
def mth(s)
yield s
end
end

class B < A
def mth(s)
super(s+'b')
end
end

class C < B
def mth(s)
super(s+'c')
end
end

C.new.mth('a') {|x| p x + 'd' } # => "abcd"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top