Working with Object Instance Data in Ruby
Objects in Ruby may have variables that are readable and writable outside of Ruby Objects that you define. In order to set variable within Object instance, you need to add it to the object’s class with an at (@) sign. This variable will be stored within Object when object runs the code.
class Car
def initialize(name)
@name = name
end
def fast
@going_fast ||=name.size > 4
@going_fast ? “I am #{name} and I am fast” : “I am slow car”
end
end
Car.new(“BMW”).fast
bmw = Car.new(“BMW”)
bmw.fast
bmw.name //produces error message “unidefined method name”
In order have access to bmw.name outside of the class, you need to call the attr_reader method or attr_accessor which depends on what you want to do with the variable (read/write) These two method provide you with gettors and settors by default. Another method called attr_writer will provide you with settors only.
class Car
attr_reader :name
end
bmw.name //will generate correct response and not the error message
It is important to note that instance variables are not defined until you initialize them via method call or write an initialize that initializes all your instance variables.
There is another Ruby specific implementation that you may find different from other languages. It involves instance and class variables. We define instance variable with one at (@) sign and class variables with two at (@@) signs. Defining variable with two at (@@) signs makes this variable available to all instances generated off the class.
Here is an example of class variable which has set two items of key-value pairs. You may find this concept of class variable similar to Java or C# constants. It is in fact similar to it.
class MyClass
@@my_class_variable = { :en => “English”, :ru=>”Russian”}
end