[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

defining a 'puts' or a 'print' for a class

Zach Dennis

11/26/2003 6:49:00 PM

I've got a class called Email and right now i have:

class Email
def initialize
....stuff here....
end

def print
return ....stuff here....
end
end


e = Email.new( ...stuff here... )
puts Email.print



But I would love to say:

puts Email

to get the same result.

Any ideas?

Thanks,

Zach





2 Answers

Mark J. Reed

11/26/2003 6:57:00 PM

0

On Thu, Nov 27, 2003 at 03:48:58AM +0900, Zach Dennis wrote:
> But I would love to say:
>
> puts Email
>
> to get the same result.
>
> Any ideas?

Define a 'to_s' method.

irb(main):001:0> class Point
irb(main):002:1> def initialize(x, y)
irb(main):003:2> @x, @y = x, y
irb(main):004:2> end
irb(main):005:1>
irb(main):006:1* def to_s
irb(main):007:2> '(' + @x.to_s + ', ' + @y.to_s + ')'
irb(main):008:2> end
irb(main):009:1> end
=> nil
irb(main):010:0> p = Point.new(3,4)
=> #<Point:0x400a3d00 @y=4, @x=3>
irb(main):011:0> puts p
(3, 4)
=> nil

If you also want your custom string form to show up in the irb inspection
(after the =>), define 'inspect', too:

irb(main):011:0> class Point
irb(main):012:1> def inspect; to_s; end
irb(main):013:1> end
=> nil
irb(main):014:0> p
=> (3, 4)
irb(main):015:0>

-Mark

Dale Martenson

11/26/2003 7:02:00 PM

0

On Wed, 2003-11-26 at 12:48, Zach Dennis wrote:
I've got a class called Email and right now i have:

class Email
def initialize
....stuff here....
end

def print
return ....stuff here....
end
end


e = Email.new( ...stuff here... )
puts Email.print



But I would love to say:

puts Email

to get the same result.

Any ideas?

You could do something like:

class Email
def initialize(email)
@email = email
end

def to_s
@email
end
end

e = Email.new("bob@mail.com")

puts e

Would that work for you?