Robert Klemme
4/16/2006 10:13:00 PM
James Herdman wrote:
> On 2006-04-16 14:00:43 -0400, Robert Klemme <bob.news@gmx.net> said:
>
>> junji wrote:
>>> i was trying the tutorials for ruby and they gave this code it seems to
>>
>>> have an error well anyway this is the code so whats wrong with it
>>>
>>> class Song2
>>> attr_reader :name, :artist, :duration
>>> end
>>> aSong = Song2.new("Bicylops", "Fleck", 260)
>>> aSong.artist #» "Fleck"
>>> aSong.name #» "Bicylops"
>>> aSong.duration #» 260
>>>
>>>
>>> can anyone tell me whats wrong here
>>>
>>> this is what the error looks like
>>> ...4:in `initialize': wrong number of arguments (3 for 0)
>>> (ArgumentError)
>>> from F:/junji/ruby-study/class/song2.rb:4
>>>
>>> Thanks all, is there another tutorial for newbies aside from what you
>>> get with FreeRide
>>
>> You'll have to define a method initialize with three parameters in order
>> to call new with three arguments.
>>
>> In your case there's an easier solution:
>>
>> Song2 = Struct.new :name, :artist, :duration
>> aSong = Song2.new("Bicylops", "Fleck", 260)
>>
>> Kind regards
>>
>> robert
>
> You're probably working through "Programming Ruby" at the moment. These
> code snippets are meant to be typed into IRB one after the other.
> Something you might want to do is write each snippet into a text file
> instead of having to type out each snippet everytime.
>
> Once you have these snippets in a text file, you can open them in IRB by
> typing the following: load 'file_name.rb'.
>
> Although there's nothing wrong with Robert's solution (which I'll talk
> about in a second), it won't help you with all of the examples in the
> book as most of them take the approach of building classes and methods
> in a piecemeal manner.
Yeah, that's likely true.
> Robert's solution uses Struct. Struct is to classes as attr_reader,
> attr_writer, attr_accessor are to getters and setters.
In other words: Struct.new creates a new class with defined properties.
> When Robert said:
> Song2 = Struct.new :name, :artist, :duration
>
> This has the same effect as typing out:
> class Song2
> attr_accessor :name, :artist, :duration
> end
No, Struct does far more. Defining the attribute accessors is just one
of them. You'll also get comparison, hash and a proper initialize
method - which is the reason I posted this suggestion.
Kind regards
robert