[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Class question

Justin To

6/19/2008 8:42:00 PM

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!!
--
Posted via http://www.ruby-....

1 Answer

Stefano Crocco

6/19/2008 8:46:00 PM

0

On Thursday 19 June 2008, Justin To wrote:
> 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