puts {"The song title is #{@name} and the
track length is
#{@duration} /n" } <- and here
Also be wary of using variables with the same name as
methods as in e.g. duration since Ruby will try and
evaluate the variable as a method or vice versa
dependant on where you are in the code.
class Song
attr_reader :name, :duration
attr_writer :name, :duration
You can also do:
attr_accessor :name, :duration
def initialize ( name, duration) @name = name @duration = duration
end
def print
puts "The song title is #{@name} and the track
length is #{@duration} "
end
def set_duration( newduration) @duration = newduration
end
There's no point having that, if you've already got a writeable
'duration' attribute Actually one of the nice things about the
attr_*-style technique is that you don't have to have methods with
'set' and 'get' in their names. Instead, you just do:
Ah, never knew that. I have coded with a get and set
mechanism since time immemorial and never really used
the accessors before. Thanks for helping me throw off
those shackles, David.
···
--- "David A. Black" <dblack@wobblini.net> wrote:
Hi --
On Sat, 12 Feb 2005, Steve Callaway wrote:
> Try this:
>
> class Song
> attr_reader :name, :duration
> attr_writer :name, :duration
You can also do:
attr_accessor :name, :duration
>
> def initialize ( name, duration)
> @name = name
> @duration = duration
> end
>
> def print
> puts "The song title is #{@name} and the track
> length is #{@duration} "
> end
>
> def set_duration( newduration)
> @duration = newduration
> end
There's no point having that, if you've already got
a writeable
'duration' attribute Actually one of the nice
things about the
attr_*-style technique is that you don't have to
have methods with
'set' and 'get' in their names. Instead, you just
do: