recursion w/ blocks; *this

  • Thread starter Nicholas Paul Johnson
  • Start date
N

Nicholas Paul Johnson

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 with ``this,'' and then would recurse to ``each''
on every child of that node.

# this doesnt work for so many reasons :)
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^[email protected]
http://manjac.ath.cx/nick
_
( ) ascii ribbon campaign - against html mail
X - against microsoft attachments
/ \ http://www.google.com/search?q=ascii+ribbon
--
 
C

Ceri Storey

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
 
M

Mark Sparshatt

Ceri said:
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
 

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,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top