help solving problem in ruby

G

Govinda Khanal

i am a beginner and having problem in linux with this code:

class Song
def to_s
"Song: #@name--#@artist (#@duration)"
end
end
song = Song.new("Bicylops", "Fleck", "2.60")
song.to_s




=> the output looks like this:


a.rb:6:in `initialize': wrong number of arguments (3 for 0)
(ArgumentError)
from a.rb:6:in `new'
from a.rb:6
 
P

pharrington

i am a beginner and  having problem in linux with this code:

class Song
  def to_s
    "Song: #@name--#@artist (#@duration)"
  end
end
song = Song.new("Bicylops", "Fleck", "2.60")
song.to_s

=> the output looks like this:

a.rb:6:in `initialize': wrong number of arguments (3 for 0)
(ArgumentError)
  from a.rb:6:in `new'
  from a.rb:6

In Ruby one can reopen a class at anytime and "monkey patch" it to add
new methods etc. Looks like you skipped the part in Programming Ruby
where the Song class was initially defined.
 
M

Michael W. Ryder

Govinda said:
i am a beginner and having problem in linux with this code:

class Song
def to_s
"Song: #@name--#@artist (#@duration)"
end
end
song = Song.new("Bicylops", "Fleck", "2.60")
song.to_s




=> the output looks like this:


a.rb:6:in `initialize': wrong number of arguments (3 for 0)
(ArgumentError)
from a.rb:6:in `new'
from a.rb:6

If you looked earlier in the chapter you would have seen an initialize
method that needs to be part of the Song class.
 
G

Govinda Khanal

thanx for your help i solve the problem ...

what actually is to_s and when we use this one?
 
M

Michael W. Ryder

Govinda said:
thanx for your help i solve the problem ...

what actually is to_s and when we use this one?

to_s converts an object to a string. In this case it converts the song
object to a format more readable than just using puts. It is also used
to convert numbers to strings, etc.
 
S

Steve Wilhelm

Govinda said:
yes, i skipped the first part. thanx for your help...

For the sake of other beginners, added initialize and a puts to last
line. Note, last line could be simplified to 'puts song'.


class Song
def initialize(name, artist, duration)
@name, @artist, @duration = name, artist, duration
end
def to_s
"Song: #@name--#@artist (#@duration)"
end
end

song = Song.new("Bicylops", "Fleck", "2.60")

puts song.to_s # => Song: Bicylops--Fleck (2.60)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top