Recursion w/ blocks; *this

Hello again,

First is, does Ruby have anything equivalent to C++‘s `this’ pointer?
I’ve tried the docs, but don’t know what to look for other than ‘this’…

Second, if I were to write a method that accepts a block, and would like
to be able to recurse in that method while allowing each of the recursions
to use the same block, how would I do that?

As an example, suppose I have a tree data structure (below), such that
each node has two children: a and b. I want to create an each'' method. Ideally, I would yield withthis,’’ and then would recurse to ``each’'
on every child of that node.

this doesnt work for so many reasons :slight_smile:

class Node
def initialize(me,a,b)
@me = me
@a = a
@b = b
end

def each

	# @this represents the calling object (see 1st question)
	yield @this

	# ideally, the same block would get passed to each of 
	# these sub calls
	@aB.each
	@b.each
end

end

Thanks y’all,

···


Nicholas Paul Johnson
nickjohnsonSPAM^H^H^H^H@virginia.edu
http://manjac.ath.cx/nick
_
( ) ascii ribbon campaign - against html mail
X - against microsoft attachments
/ \ http://www.google.com/search?q=ascii+ribbon

Hello again,

First is, does Ruby have anything equivalent to C++‘s `this’ pointer?
I’ve tried the docs, but don’t know what to look for other than ‘this’…

Aye. You’re looking for the ‘self’. eg:
irb(main):001:0> self
=> main

Second, if I were to write a method that accepts a block, and would like
to be able to recurse in that method while allowing each of the recursions
to use the same block, how would I do that?

def a_method(arg, &block)
if arg > 10
a_method(arg.succ, &block)
end
end

More details here: http://rubycentral.com/book/tut_methods.html

As an example, suppose I have a tree data structure (below), such that
each node has two children: a and b. I want to create an each'' method. Ideally, I would yield with this,‘’ and then would recurse to ``each’’
on every child of that node.

class Node
def initialize(left, right)
@left = left
@right = @right
end

def each(&block)
	block.call(self)
	@left.each(&block) if @left
	@right.each(&block) if @left
end

end

···

On Sun, Apr 04, 2004 at 05:58:04PM +0900, Nicholas Paul Johnson wrote:


Ceri Storey cez@necrofish.org.uk

Ceri Storey wrote:

def a_method(arg, &block)
if arg > 10
a_method(arg.succ, &block)
end
end

At the risk of sounding pendantic I just have to point out that this
will recurse infinitely if arg > 10. I think you meant

def a_method(arg, &block)
if arg < 10
a_method(arg.succ, &block)
end
end

···


Mark Sparshatt

You may be pedantic, but entirely correct. Cheers. :slight_smile:

···

On Sun, Apr 04, 2004 at 06:25:02PM +0900, Mark Sparshatt wrote:

At the risk of sounding pendantic


Ceri Storey cez@necrofish.org.uk