From: dblack@... Date: 2006-11-17T01:24:36+09:00 Subject: Re: basic mistake? Hi -- On Fri, 17 Nov 2006, Nia wrote: >> Hal is correct, moving it into initialize solves the problem. >> >> It appears that declaring the instance variable at the class >> level makes it an instance variable of the class, rather than >> of the object of the class being created when initialize is called. >> >> In short, declare your instance attributes inside initialize. >> >> Cheers >> Chris >> > > hehe, i knew it was some basic mistake. thank you all very much. so > is it wrong to declare a variable outside a method? cause i usually > do that a lot, It's wrong to initialize a variable in one scope and try to use it in another :-) Actually there are (at least) two things to keep in mind: 1. Local variables are visible in their local scope. So here: class C x = 1 def meth x = 2 end end the two x's are totally unrelated. 2. Instance variables are scoped to, or associated with, "self". In other words, an instance variable (@var) always belongs to whatever object is "self" at that point. Here: class C @x = 1 # (a) def meth @x = 2 # (b) end end you're dealing with two selfs (selves?). At (a), self is the class object itself, C. At (b), self will be whatever instance of C calls the methods "meth". So, since there are two selfs, the two @x's are totally unrelated to each other. David -- David A. Black | dblack@rubypal.com Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org