Ruby is an object-oriented programming language. It is based on concept of ‘object’ which are data structure containing data in the form of methods. Ruby lets us allows to add methods to an already loaded class or create our own classes where we can create custom-made methods with endless possibilities.
Ruby is an interesting programming language because it lets us create our own class and its own methods. While writing own class and methods, one will come across a concept called instance variable and methods. Instance variable, which is followed after ‘@‘, are variable that belong to a particular object instance and is not available to methods outside its class. Remember that when writing a Ruby class, its title or name has to be capitalized followed by the word ‘class’. An easy example of a Ruby class is shown below with an instance variable which can be access throughout all the methods within the class:
class Person attr_reader :first_name, :last_name, :age def initialize(first_name, last_name, age) @first_name = first_name @last_name = last_name @age = age end def full_name puts "#{@first_name} #{@last_name}" end end andrew = Person.new('Andrew', 'Kim', 29) andrew.full_name OUTPUT => Andrew Kim andrew.age OUTPUT => 29
As shown above, instance variable was used in initialize method and full_name method. Initialize method is the usual constructor to create new objects. And it can only be used within the class it is written in. It can thought as variable or type of data that can be accessed by every methods within the class. Remember that it is only used within the class.
Class can be simply thought of as type of objects that can be oriented upon. Integers and strings are type of classes. They have different type of methods that can be applied upon for their class only. They can have common methods like .sort which can sort numbers numerically or the string alphabetically. But they have their own different unique methods. Strings have .upcase method which turns all the alphabets into upper cases but this method can’t be used in integers because numbers cannot be a lower case or upper case.