sluther sluther - 1 month ago 17
Ruby Question

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?

Answer
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