Excerpts from Rocky D.'s message of 2013-09-08 08:26:53 +0200:
Hi there. I just started learning Ruby and here is the code I'm stuck
at:
class Greeter
def initialize(name = "World")
@name = name
end
def say_hi
puts "Hi #{@name}!"
end
end
Okay, in this program I declared variable name named "name" using @
symbol, so it's "@name" declared. My question is do I need to use
"initialize" everytime I create a variable?
I don't exactly understand what you mean. The initialize method is
automatically called whenever you create an instance of a class using
its .new method:
gr = Greeter.new #this calls initialize
Variables starting with @ are instance variables, that is variables tied
to a specific object. Usually, you create instance variables in
initialize so that they're availlable immediately after the object has
been created. This is not a requirement, however. For instance, if you
want to remember that your greeter has already greeted someone, you
could do this in your say_hi method:
def say_hi
puts "Hi #{name}"
@greeted = true
end
You create an instance variable in say_hi without having created it
in initialize. Personally, I don't like this much because I usually
prefer to have all instance variables visible at a glance, which is
easier if you create them all in the same place, with initialize being
the obvious choice.
Note that in ruby you don't "declare" variables: you just create them by
assigning a value to them. You can also use an instance or class variable you
haven't created yet: its value will be nil. In this case, however,
ruby will complain by issuing a warning (if you have warnings enabled).
class X
def test_var
p @var
end
end
X.new.test_var
#=> nil
#If warnings are enabled, you'll get a warning saying
"warning: instance variable @var not initialized"
I hope this helps
Stefano