PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.ruby > Class question
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
Class question

Réponse
 
LinkBack Outils de la discussion
Vieux 19/06/2008, 21h41   #1
Justin To
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut 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 method
`empty?' for nil:NilClass (NoMethodError)
from TEST.rb:23

Why is my exceptions hash a NilClass??

Thanks!!
--
Posted via http://www.ruby-forum.com/.

  Réponse avec citation
Vieux 19/06/2008, 21h46   #2
Stefano Crocco
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Class question

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 s

Stefano


  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 06h16.


Édité par : vBulletin® version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières ©2000-2008
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 0,12429 seconds with 10 queries