开发者

Why am I getting "undefined method '+' for nil:NilClass"?

开发者 https://www.devze.com 2023-01-12 07:42 出处:网络
isn\'t + an operator?why would it not be defined? here\'s my code: Class Song @@plays = 0 def initialize(name, artist, duration)

isn't + an operator? why would it not be defined?

here's my code:

Class Song
  @@plays = 0
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
    @plays = 0
  end
  attr_reader :name, :artist, :duration,
 开发者_如何转开发 attr_writer :name, :aritist, :duration
  def play
    @plays += 1
    @@plays += 1
    "This Song:  #@plays play(s).  Total #@@plays plays."
  end
  def to_s
    "Song: #@name--#@artist (#@duration)"
  end
end


First, this code doesn't even run: class on Line 1 needs to be spelled with a lowercase c, and you can't have a comma after the last item in a statement (your attr_reader line). I don't get a NoMethodError after fixing those and running Song.new or Song#play or Song#to_s.

Anyway, you will always get that NoMethodError when you try adding anything to a nil value:

>> nil + 1
NoMethodError: undefined method `+' for nil:NilClass
    from (irb):1
>> nil + nil
NoMethodError: undefined method `+' for nil:NilClass
    from (irb):2
>> # @foo is not defined, so it will default to nil
?> @foo + 2
NoMethodError: undefined method `+' for nil:NilClass
    from (irb):4

So you might be trying to add something to an uninitialized instance variable... or it could be anything. You always need to post full, minimal code to duplicate an error if you want to be helped properly.


+ is defined on numbers (among other things). However, as the error message says, it is not defined on nil. This means you can't do nil + something and why would you?

That being said, you're actually not calling nil + something anywhere in the code you've shown (you're initializing both @plays and @@plays to 0, and you're not setting them to nil at any point). And as a matter of fact your code runs just fine once you remove the two syntax error (Class should be class and there should be no comma after :duration). So the error is not in the code you've shown.


maybe you should include @@plays = 0 in your initialize method?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号