Class question

class Box
attr_reader :exceptions

def initialize

  exceptions = Hash.new

end

  def exceptions?
    if(!exceptions.empty?)
      puts "error"
    else
      puts "No exceptions found."
    end
  end

end

box = Box.new

box.exceptions?

This prints out the error: TEST.rb:11:in exceptions?': undefined methodempty?’ for nil:NilClass (NoMethodError)
from TEST.rb:23

Why is my exceptions hash a NilClass??

Thanks!!

On Thursday 19 June 2008, Justin To wrote:

    if(!exceptions.empty?)

box.exceptions?

This prints out the error: TEST.rb:11:in exceptions?': undefined methodempty?’ for nil:NilClass (NoMethodError)
from TEST.rb:23

Why is my exceptions hash a NilClass??

Thanks!!

The error is in the initialize method. Writing

exceptions = Hash.new

you assign the hash to a local variable called exceptions, not to the
instance
variable called @exceptions, which is the variable the method generated
by
attr_reader refers to (instance variables always start with @).

By the way, in the exceptions? method, you’re using the exceptions
method.
This isn’t wrong, but it’s usually not necessary, since exceptions? is
an
instance method of class Box, which means it can access the @exceptions
instance variable directly.

I hope this helps

Stefano