From: tsela.cg@... Date: 2007-04-04T22:30:11+09:00 Subject: Re: Everything is a object? On Apr 4, 2:43 pm, Jamal Soueidan wrote: > > So until I assign something to it, the interpreter would know nothing > about what object it is. > Of course not, the interpreter cannot read your mind. > In C# you can declare every variable what type it is like this: > String mystring; > > I assume I could do that in Ruby also: > @var = String.new > Except that when you're doing that you're not declaring what type of variable @var is, you're just assigning a new empty string to @var ( it's the equivalent of @var = ""). That's a big difference between Ruby and C#: in Ruby you *cannot* declare a variable, because that does not mean anything (variables in Ruby don't have "types" attached to them, as in C# and other statically typed languages, so declaring them would be meaningless). > But no need since Ruby would take care of this automatic when you assign > something to variables. > Yes. > When I write attributes in my code: > attr_assoccer :var > I assume you mean: attr_accessor :var > I assume > then < the interpreter knows only that @var is a object (base > class)? > No. "attr_accessor" only defines two instance methods within the class you're using it in, which allow @var (which is a private instance variable) to be accessible from outside its object. In other words, class SomeClass attr_accessor :var end is exactly equivalent to: class SomeClass def var @var end def var=(param) @var = param end end Both allow you to do: instance = SomeClass.new instance.var = "Hello world!" puts instance.var However, what happens is that when you try to use an instance variable that has never been assigned, Ruby gives it the "nil" value automatically. Exactly why it does that with instance variables and not with local variables I don't know, but they are used in different enough ways that the difference should not be bothersome. > So before I can use @var. > > - I can either declare it, so the interpreter knows something about it > (base class object) Except that you can't declare it. At most you can assign to it some object value. Nothing prevents you from assigning it to a different and unrelated object value later (it can be of any class!). > OR > - I can assign something to it, so the interpreter knows what type it is > > @var = 'string' > That is actually the only thing you can do, since declaration don't exist in Ruby. However, for instance variables (variables with a @ in front of them), you needn't do that, as Ruby gives them the nil value automatically. All the other variable types (local variables, constants and class variables) need to be assigned to before use. Christophe.