gao_bo
(gao bo)
1
hi, everyone
today i typed the code below in my IDE
class Song
attr_reader :name, :artist, :duration
attr_writer :duration
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def durationInMinutes
@duration/60.0
end
def durationInMinutes=(value)
@duration = (value * 60).to_i
end
end
class Song
def to_s
"song: #{@name}--#{@artist} (#{@duration})"
end
end
aSong = Song.new("hello", "zhutou","332")
puts aSong.to_s
puts aSong.durationInMinutes
And i tried to run it, but the error occured:
song: hello--zhutou (332)
song.rb:12:in `durationInMinutes': undefined method `/' for "332":String
(NoMethodError)
from song.rb:29
Why?
Thanks!
U passed "332" as a string so it was stored as a string. Take the quotes off 332 or better, in ur init, say @duration=duration.to_i
Mike
···
-----Original Message-----
From: "gao bo" <gaob06@gmail.com>
Date: Sat, 19 May 2007 11:07:17
To:ruby-talk@ruby-lang.org (ruby-talk ML)
Subject: Why "NoMethodError" occurs
hi, everyone
today i typed the code below in my IDE
class Song
attr_reader :name, :artist, :duration
attr_writer :duration
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def durationInMinutes
@duration/60.0
end
def durationInMinutes=(value)
@duration = (value * 60).to_i
end
end
class Song
def to_s
"song: #{@name}--#{@artist} (#{@duration})"
end
end
aSong = Song.new("hello", "zhutou","332")
puts aSong.to_s
puts aSong.durationInMinutes
And i tried to run it, but the error occured:
song: hello--zhutou (332)
song.rb:12:in `durationInMinutes': undefined method `/' for "332":String
(NoMethodError)
from song.rb:29
Why?
Thanks!