NameError:未定义的局部变量或方法

时间:2013-07-23 20:51:35

标签: ruby

我编写了一个非常简单的Ruby脚本,它在编译时失败了。不知道究竟是什么问题。任何建议都表示赞赏。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

写如下

def duration=(new_duration)
   @duration=new_duration
end

您已在此行@duration=new _duration中添加了一个额外的空格,您不应该在方法参数列表new_duration中将该参数设为def 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

答案 2 :(得分:0)

看起来你在new和_direction之间有一个空格。否则我没有看到问题。