2013-07-23 116 views
-2

我寫了一個非常簡單的Ruby腳本,它在編譯時失敗。不知道究竟是什麼問題。任何建議表示讚賞。NameError:未定義的局部變量或方法

class Song 

def initialize (name, album, duration) 
     @name = name 
     @album = album 
     @duration = duration 
end 

def duration=(new_duration) 
     @duration=new _duration 
end 

def to_s 
    "Song: #@name for #@album -- #@duration \n" 
end 

song = Song.new("ABC", "I don't lie...", 2.04) 

print song.to_s 

song.duration = 3.89 

print song.to_s 

編譯我收到以下錯誤後:

ruby Song.rb 
Song: ABC for I don't lie... -- 2.04 
1. ABC 
2. I don't lie... 
3. 2.040000 
NameError: undefined local variable or method `_duration' for #<Song:0x3b500efd> 
duration= at Song.rb:21 
Song at Song.rb:37 
(root) at Song.rb:1 
+1

您只需查看指定的行。你有一個工作! – Shoe

回答

0

寫如下

def duration=(new_duration) 
    @duration=new_duration 
end 

你已經把一個額外的空間,在這條線@duration=new _duration,你不應該爲你請在方法參數列表def duration=(new_duration)中將該參數設置爲new_duration

完全糾正代碼:

class Song 

    def initialize (name, album, duration) 
    @name = name 
    @album = album 
    @duration = duration 
    end 

    def duration=(new_duration) 
    @duration=new_duration 
    end 

    def to_s 
    "Song: #@name for #@album -- #@duration \n" 
    end 
end 

song = Song.new("ABC", "I don't lie...", 2.04) 

print song.to_s 

song.duration = 3.89 

print song.to_s 
# >> Song: ABC for I don't lie... -- 2.04 
# >> Song: ABC for I don't lie... -- 3.89 
+0

感謝您的快速響應和更正。我看到它出錯的地方。 – itsh

0

看起來你在新的_direction之間的空間。否則,我不會看到問題。

1

您應該完全刪除該方法,並用attr_writer替換。不太容易出錯並且速度更快:

class Song 
    attr_writer :duration 

    def initialize (name, album, duration) 
    @name = name 
    @album = album 
    @duration = duration 
    end 

    def to_s 
    "Song: #@name for #@album -- #@duration \n" 
    end 
end 
相關問題