Class question

J

Justin To

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 method
`empty?' for nil:NilClass (NoMethodError)
from TEST.rb:23

Why is my exceptions hash a NilClass??

Thanks!!
 
S

Stefano Crocco

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 method
`empty?' 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,901
Members
47,439
Latest member
elif2sghost

Latest Threads

Top