Re: Understanding global variables.
- From: 7stud -- <bbxx789_05ss@xxxxxxxxx>
- Date: Fri, 15 Apr 2011 13:10:53 -0500
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/.
.
- References:
- Understanding global variables.
- From: Fily Salas
- Re: Understanding global variables.
- From: Fily Salas
- Understanding global variables.
- Prev by Date: [ANN] Rails 3.0.7.rc2
- Next by Date: Re: Extract a range i.e. svr[100..130] ?
- Previous by thread: Re: Understanding global variables.
- Next by thread: Re: Understanding global variables.
- Index(es):
Relevant Pages
|