Tim Ferrell
2/11/2005 8:15:00 PM
try this...
#---- test.rb ----
class Song
attr_writer :name, :duration
def initialize(name, duration)
@name = name
@duration = duration
end
def print
puts "The song name is #{@name} and the duration is {@duration}\n\n"
end
end
class Song2
attr_writer :name, :duration
def initialize(name, duration)
@name = name
@duration = duration
end
def to_s
return "The song name is #{@name} and the duration is duration}\n\n"
end
end
if $0 == __FILE__
# create an instance of Song
asong = Song.new("Some Bangin' Tune", 2443)
puts asong
asong.print
# change attribute values
asong.name = "A New Tune"
asong.duration = 3750
puts asong
asong.print
# create an instance of Song2
asong = Song2.new("Another Bangin' Tune", 2660)
puts asong
end
#---- end test.rb ----
a few things to note... in your original version you had:
puts { "text here" }
Ruby sees the braces as a block associated with the call to puts, rather
than an argument to puts, which is why it was printing blank lines
I also think attr_writer implies attr_reader so you don't need both when
using attr_writer.
Also, by adding a method to_s to a class (as in Song2), it is
automatically called when you "puts" the varas opposed to just printing
out the address
Hope this helps...
Cheers,
Tim
Ghelani, Vidhi wrote:
> Hey,
>
>
>
> I am trying to test some of my code. Here it is :
>
> ************************************************************************
> *************************
>
> class Song
>
>
>
> def duration= (newDuration)
>
> @duration = newDuration
>
> end
>
>
>
> def initialize(name, duration)
>
> @name = name
>
> @duration = duration
>
> end
>
>
>
> attr_reader :name, :duration
>
> attr_writer :name, :duration
>
>
>
> def print
>
> puts {"The song title is #{@name} and the track length is
> #{@duration} /n" }
>
> end
>
>
>
>
>
> end
>
>
>
>
>
> asong = Song.new("Mahi Ve", 2443)
>
> asong.print
>
> asong.name
>
> asong.duration
>
>
>
> ************************************************************************
> ***********************
>
> However, this does not print anything. There are no errors showing up
> either. All that happens is that it prints blank lines.
>
>
>
> Does anyone know where I am going wrong ?
>
>
>
> Any help would be appreciated.
>
>
>
> Thanks,
>
> Vidhi
>
>
>
>