Method usable as instance and as class method

M

Michael Perle

Hi Ruby Folks,

What do you think would be the best way
to provide one and the same method as a
class method and as an instance method.

I did not find any examples, and am asking myself
if the call of the class method from the instance
method is the real thing.

1. Is there a better way?
2. Does it make any difference if I use
'def self.method' or 'def ClassName.method'
3. Why does self.method not work in the def of
an instance method? (See 2nd comment below.)

--- Start of sample code ---

class TextCase

def self.up(txt)
# Would TextCase.up(txt) be any different?
txt.upcase
end

def up(txt)
TextCase.up(txt)
# Why not self.up(txt)?
# Tried it and got a 'stack level too deep ...' error
end

end

tc = TextCase.new
puts tc.up('abc')
puts TextCase.up('def')

--- End of sample code ---

Thank you very much for your ideas.
MP
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top