From: balcer Date: 2005-08-22T19:01:18+09:00 Subject: Re: Ruby beginner question 2 Robert Klemme napisaƂ(a): > Jeff Wood wrote: > >>Alucard wrote: >> >> >>>Hi all! >>> >>>I'm using ruby 1.82. This is the code copy from www.ruby-lang.org, >>>programming ruby. >>> >>>And I found that both the following code cannot run, with the >>>following error occur: >>> >>>song_2.rbw:4:in `initialize': wrong number of arguments (3 for 0) >>>(ArgumentError) >>>from song_2.rbw:4:in `new' >>>from song_2.rbw:4 >>> >>>So, what is going wrong? >>> >>>Thanks in advance! >>> >>>CODE: >>>class Song >>> def name >>> @name >>> end >>> def artist >>> @artist >>> end >>> def duration >>> @duration >>> end >>>end >>>aSong = Song.new("Bicylops", "Fleck", 260) >>>aSong.artist >>>aSong.name >>>aSong.duration >>> >>> > > #------------------------------------------------------------------------- > ------------------- > >>>class Song >>> attr_reader :name, :artist, :duration >>>end >>>aSong = Song.new("Bicylops", "Fleck", 260) >>>aSong.artist >>>aSong.name >>>aSong.duration >>> >>> >>> >>> >>> >> >>Your objects have no constructor method ... therefore, it's simply >>relying on the constructor from Object ( which is implicitly >>inherited ). >> >>So, simply add >> >>def initialize( name, artist, duration ) >>@name = name >>@artist = artist >>@duration = duration >>end >> >>within either of your class definition examples... then they'll work. >> >>The inherited constructor from Object takes no parameters, and that's >>why you are getting the "initialize wrong number of arguments 3 for >>0"... You're passing 3 to a no argument constructor... > > > A simpler alternative is to just use Struct: > > # direct > Song = Struct.new :name, :artist, :duration > > class Song > # other methods > end > > Kind regards > > robert > > Sometimes, during the proces of teaching it is not a good idea to give and alternative :) Jacek