Re: Understanding global variables.



Fily Salas wrote in post #992993:

This may be confusing because I have never heard about “SELF” statement,
“INITIALZE” method and the “:” notation, I guess I need to read more
about the language.


Knowing which object is 'self' is sort of an intermediate topic, but it
is critical to understanding how ruby works.

What would happen if I position a variable using the wrong syntax? In
other words if I position a variable where an instance variable would
normally go but without the @ will Ruby get confused and treat this
differently and may get an error or the interpreter will simply use it
and keep track of what kind of variable it is by itself.


A variable name that is not preceded by an '@', is called a 'local
variable', and a local variable ceases to exist once the method ends.
Here is an example:

class Dog
def initialize(a_name, a_color)
@name = a_name
color = a_color
end

def name
@name #same as 'return @name'
end

def name=(str)
@name = str
end

def color
@color #same as 'return @color'
end


end

my_dog = Dog.new('Spot', 'black')
#Calling new() automatically causes initialize()
#to execute.

puts my_dog.name #=> Spot
my_dog.name = 'Max'
puts my_dog.name #=> Max

puts my_dog.color #=> <nothing>


Any good tutorial about variables in Ruby?

"Beginning Ruby (2nd ed)" by Cooper

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



Relevant Pages

  • Re: Ruby Basics
    ... I bought a copy of the Ruby equivalent to the Perl Camel Book ... def moo ... puts "this is the first definition" ...
    (comp.lang.ruby)
  • Re: Reusing chunks of code
    ... def testobj.homePlay ... puts 'nope' ... But that code just wraps a definition around a ruby method, ...
    (comp.lang.ruby)
  • Re: Desktop multi-plataform ruby app
    ... regular ruby, so I assume the same is valid for jruby only with the prefix ... Starting out with Glade and Ruby ... def initialize ... puts "This script creates a class and a main program that shows a ...
    (comp.lang.ruby)
  • Re: what do you think of this code?
    ... # The Unix tool 'ls' implemented in ruby ... def initialize ... else puts "no Argument - define path" ... want the nil error to trickle up. ...
    (comp.lang.ruby)
  • Re: Dynamic stuff and books
    ... Since almost everything in Ruby is an expression, ... def singclass ... puts "Sync" ... synchronize:syncme ...
    (comp.lang.ruby)