In Ruby, an instance variable is a variable declared inside a class that's specific to each instantiated object of the class it's defined in (i.e. each class instance has a separate copy of an instance variable). It is:
- Declared inside instance methods, or the constructor method;
- Created by adding a single at-sign (
@) before a variable name (e.g.
- Accessible by class instance methods, as well as derived classes (or included modules);
- Not accessible by class methods;
- Always private to outside access.
Consider, for example, the following
Person class that has two instance variables; "
@name" and "
class Person def initialize(name, age) @name = name @age = age end end
To get/set these instance variables from outside the class, you must create getter/setter methods. For example, you can use the
attr_reader accessor method to auto-generate getters for the instance variables, like so:
class Person def initialize(name, age) @name = name @age = age end attr_reader :name, :age end person1 = Person.new("bob", 34) puts person1.name #=> "bob" puts person1.age #=> 34 person2 = Person.new("john", 22) puts person2.name #=> "john" puts person2.age #=> 22
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.