From: Wesley J Landaker Date: 2004-02-04T06:46:38+09:00 Subject: Re: Newbie question --Boundary-02=_5aBIA7kcgqDHV0X Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Content-Description: signed data Content-Disposition: inline On Tuesday 03 February 2004 2:35 pm, Stephen Taylor wrote: > We are two grey-haired programmers studying Ruby and have a question > so basic we can't believe we 're unable to find an answer in "The > Ruby Way" and "Ruby in 21 Days" or the online material. > > Our class Money holds pennies as Fixnum values and its to_s method > returns a string with the currency symbol prefixed. (Leave commas and > decimal point for later.) > > class Money > attr_accessor :value > def to_s > '=A3' + @value.to_s > end > end > > permits: > > m =3D Money.new > m.value=3D 1234 > puts m.to_s > "=A31234" > > Question: can we create and set in one move? We imagine > > n =3D Money.new(1234) > > But if we: > > def Method.new(amt) > initialize > @value =3D amt > end > > we get: > > n =3D Money.new(1234) > n.to_s > "1234" > n.class > "Fixnum" > > Advice? You don't want to override the 'new' method, you want to override the=20 'initialize' method in your class. Something like this: class Money def initialize(amt) @value =3D amt.to_i end def to_s ' ' + @value.to_s end end m =3D Money.new(1234) m.to_s=20 m.class=20 =2D-=20 Wesley J. Landaker OpenPGP FP: 4135 2A3B 4726 ACC5 9094 0097 F0A9 8A4C 4CD6 E3D2 --Boundary-02=_5aBIA7kcgqDHV0X Content-Type: application/pgp-signature Content-Description: signature -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQBAIBa58KmKTEzW49IRAi3KAJ4jXfpaSCdwGw1ATPiw/fvn1a2dDQCdGzf3 fnds3XbA33NQLZxnF2+4opw= =uqE9 -----END PGP SIGNATURE----- --Boundary-02=_5aBIA7kcgqDHV0X--