[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

ruby modules and classes

surendra

3/1/2006 2:58:00 PM

2 Answers

Ross Bamford

3/1/2006 3:12:00 PM

0

On Wed, 2006-03-01 at 23:57 +0900, Surendra Singhi wrote:
> Hello,
>
> When I try the code below I get an error. Why is it so? Am I misunderstanding
> how modules behave? How should the module be written so that `who_am_i' is
> added as a method to the class Phonograph.
>
> module Debug
> def self.who_am_i?
> "#{self.class.name} (\##{self.id}): #{self.to_s}"
> end
> end
> class Phonograph
> include Debug
> end
> Phonograph.who_am_i?

Depends what you want, but how about:

module Debug
def who_am_i?
"#{self.class.name} (\##{self.object_id}): #{self.to_s}"
end
end

class Phonograph
class << self
include Debug
end
end

p Phonograph.who_am_i?

Or, if you want it as both class and instance methods, I like this
trick:

module Debug
def who_am_i?
"#{self.class.name} (\##{self.object_id}): #{self.to_s}"
end

def self.included(othermod)
othermod.extend(self)
end
end

class Phonograph
include Debug
end

p Phonograph.who_am_i?
p Phonograph.new.who_am_i?

(P.s. do you know about Object#inspect?)

--
Ross Bamford - rosco@roscopeco.REMOVE.co.uk



surendra

3/2/2006 1:16:00 PM

0