I was under the impression (newbie alert) that @name was for instances
and @@name was for classes as a whole (ie, @@ variables change that
value in all instances of Class). Is there a way to have variables that
apply to all instances of a Class?
It seems that @name reverts back once I leave the scope of any method
that manipulates it.
As you’ve learned from some of the other responses, @name is an
instance variable. Each instance variable belongs to one object. You
can always tell which object: it’s whatever the default object
(self) is, at the point where the “@var” is executed.
Note that self changes between a class definition and an instance
method definition:
class Person
puts self
def some_method
puts self
end
end
In the top level of the class definition, self is the actual class
object (Person), but inside an instance method, it’s the instance
(indicated by the #<Person…> expression).
So… @name in the outer scope is actually an instance variable
belonging to the class object, while inside any instance method, @name
is an instance variable belonging to the instance. The two @name’s
have no connection to each other at all.
You can use class variables to get a variable that can be seen in both
scopes, but if you’ve got a property like “name” and you find yourself
manipulating it outside of any instance method, something’s probably
in need of tweaking in the program design (since the name of any
particular instance shouldn’t be of concern at the class level).
I was under the impression (newbie alert) that @name was for instances
and @@name was for classes as a whole (ie, @@ variables change that
value in all instances of Class). Is there a way to have variables
that
apply to all instances of a Class?
Use an initialize method:
class Person
def initialize(name=“Anonymous”) @name = name
end
attr_accessor :name
def to_s
“My name is #{@name}”
end
end
person = Person.new
puts person # → My name is Anonymous
person.name = “Fred”
puts person # → My name is Fred
I was under the impression (newbie alert) that @name was for instances
and @@name was for classes as a whole (ie, @@ variables change that
value in all instances of Class). Is there a way to have variables that
apply to all instances of a Class?
Oops, I read the question too quickly. Sorry. David Black has the
right explanation.
-Adam
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.