sluther
sluther

Reputation: 1724

Undefined method '[]=' for nil:NilClass

I have the following code:

class Derp
    @state = Hash.new

    def run
        @state[:ran] = true
    end
end

derp = Derp.new
derp.run

Which results in the following error:

NoMethodError: undefined method `[]=' for nil:NilClass
    from (irb):4:in `run'
    from (irb):8
    from /usr/local/bin/irb:11:in `<main>'

I'm pretty new to Ruby, so I'm not sure exactly what's going on here. Anyone have any ideas?

Upvotes: 0

Views: 58

Answers (1)

Ursus
Ursus

Reputation: 30056

class Derp
  def initialize
    @state = Hash.new
  end

  def run
    @state[:ran] = true
  end
end

derp = Derp.new
derp.run

The problem in your code is that in the way you did the hash is assigned to the instance variable @state of the class object Derp, not to Derp's objects. Instance variables of the class are different from instance variables of that class’s objects. You could use that variable in class methods. E.g.

class Derp
  @state = 42

  def self.state
    @state
  end
end

puts Derp.state # 42

Upvotes: 3

Related Questions