Fily S. 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 #color will cease to exist after method ends
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 any initialize()
#method defined in Dog to execute.
puts my_dog.name #=> Spot
my_dog.name = ‘Max’
puts my_dog.name #=> Max
puts my_dog.color #=>
Note that the following ‘getter’ and ‘setter’ methods are so common:
def name
@name #same as ‘return @name’
end
def name=(str)
@name = str
end
…that you can replace them by:
attr_accessor :name
and ruby will create the getter and setter methods for you. The
following:
attr_accessor :name
is really the method call:
attr_accessor(:name)
:name is what’s called a “symbol”, which is sort of like a constant
string that has an integer id associated with it. Normally, when you
compare the equality of strings like ‘abc’ and ‘abd’, ruby has to check
each character of the strings for equality. With symbols, ruby just has
to check the integer id’s for equality, e.g.
:abc => id = 1234
:abd => id = 5678
so to compare the symbols :abc and :abd, ruby just compares their ids:
if (1234 == 5678)
puts ‘the symbols :abc and :abd are equal’
else
puts ‘they’re not equal’
end
…which is more efficient than comparing every character of the symbol.
A
lot of ruby methods take symbols as arguments, and attr_accessor() is
one of them.
Any good tutorial about variables in Ruby?
“Beginning Ruby (2nd ed)” by Cooper