From: Jim Weirich Date: 2004-02-04T06:48:32+09:00 Subject: Re: Newbie question Stephen Taylor said: > 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. Perhaps another grey-haired programmer can answer :-) > > 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.) [... code elided ...] > Question: can we create and set in one move? We imagine > > n = Money.new(1234) > > > But if we: > > def Method.new(amt) > initialize > @value = amt > end Remember that new is a class method, therefore references to @value inside of new will reference the value attribute of the *class* object Money, not an instance of Money. Fortunately, the built-in version of new calls initialize after the object is allocated. Initialize is an instance method, so you can do what you need in it. For example class Money def initialize(value) @value = value end # ... rest of class here ... end n = Money.new(1234) # Should now work. -- -- Jim Weirich jim@weirichhouse.org http://onestepback.org ----------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)