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

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…