From: James Edward Gray II Date: 2007-04-04T21:56:48+09:00 Subject: Re: Everything is a object? On Apr 4, 2007, at 7:43 AM, Jamal Soueidan wrote: > Eleanor McHugh wrote: >> On 4 Apr 2007, at 11:02, Jamal Soueidan wrote: >>> I have been reading about these various boolean returns, how Ruby >>> look >>> at them, as you mentioned false and nil is the only objects which >>> are >>> considered false. >>> >>> But I thought you did not need to define/declare any variables >>> before >>> using it, but this has been misunderstood, you should somehow >>> assign the >>> variable to something before trying to use it, since Ruby "Still" >>> don't >>> know what object it is, right? >> >> The point is that you don't have to define a variable before you make >> an assignment to it, much like in older variants of BASIC. Assignment >> implicitly declares the variable to exist within the specified scope. >> However until you make an assignment the interpreter is not aware of >> the variable's existence (because logically it does not yet exist) >> and so attempts to reference it will fail to produce a reference to >> an object. An attempt will also be made to apply the token to the >> current object as a method, and if this too fails then the >> interpreter has no choice but to flag an error condition because >> semantically your program is broken - it makes no sense. > > :D > > So until I assign something to it, the interpreter would know nothing > about what object it is. I think it's probably better to say that until you assign it, it doesn't exist. But yes, you are on the right track here. > 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 > > But no need since Ruby would take care of this automatic when you > assign > something to variables. C# cares what type a variable is. It uses that information for things like method lookup. Ruby does not. A variable can hold whatever you like: str = String.new # ... str = 5 # Ruby doesn't care that it's not a String now This is called "dynamic typing" and is one of the great features of Ruby. It does take some getting use to though, if you are joining us from a statically typed language. > When I write attributes in my code: > attr_assoccer :var > > I assume > then < the interpreter knows only that @var is a object > (base > class)? > > So before I can use @var. Actually, the it doesn't exist until you define it rule only applies to local variables: $ ruby -e 'p local_var' -e:1: undefined local variable or method `local_var' for main:Object (NameError) $ ruby -e 'p @inst_var' nil $ ruby -e 'p $global_var' nil However, the last two issue warnings when enabled (which I recommend): $ ruby -we 'p @inst_var' -e:1: warning: instance variable @inst_var not initialized nil $ ruby -we 'p $global_var' -e:1: warning: global variable `$global_var' not initialized nil Hope that helps. James Edward Gray II