Recursion in a class method

I

Iain Barnett

Hi,

If I've written a class method that calls itself recursively is there a =
problem or any difference between doing something like this:

class << self
def mymeth( n )
blah blah...
=20
mymeth( n + 1)
end
end


as opposed to this?

class << self
def mymeth( n )
blah blah...

Classname.mymeth( n + 1 )
end
end

I wrote something a few minutes ago in the first way, and it works =
(those virgin sacrifices must be working their magic) but wondered if =
that's A Really Bad Thing To Do=99, or if it's more like wearing socks =
with sandals on a warm day?


Regards,
Iain
 
R

Robert Klemme

Hi,

If I've written a class method that calls itself recursively is there a p=
roblem or any difference between doing something like this:
class << self
=A0def mymeth( n )
=A0 =A0blah blah...

=A0 =A0mymeth( n + 1)
=A0end
end


as opposed to this?

class << self
=A0def mymeth( n )
=A0 =A0blah blah...

=A0 =A0Classname.mymeth( n + 1 )
=A0end
end

I wrote something a few minutes ago in the first way, and it works (those=
virgin sacrifices must be working their magic) but wondered if that's A Re=
ally Bad Thing To Do=99, or if it's more like wearing socks with sandals on=
a warm day?

Even simpler

irb(main):006:0> class X
irb(main):007:1> def self.r(n) p n; r(n-1) if n > 0 end
irb(main):008:1> end
=3D> nil
irb(main):009:0> X.r 5
5
4
3
2
1
0
=3D> nil

You do not need "Classname." because "self" is the class instance.
Actually placing the class name could do more harm than good (think of
"private" and renaming the class).

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
I

Iain Barnett

You do not need "Classname." because "self" is the class instance.
Actually placing the class name could do more harm than good (think of
"private" and renaming the class).

Kind regards

robert

Ok, thanks very much. Nice to know my natural way was the best way :)

Regards,
Iain
 

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,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top