Alright class. Who knows the definition for the word class?
One of the english definition of class.
noun
noun: class; plural noun: classes
1.
a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.
Ruby’s definition of what is a class?
A class is a blueprint from which objects are created. The object is also called as an instance of a class. For Example, the animal is a class and mammals, birds, fish, reptiles, and amphibians are the instances of the class. Similarly, the sales department is the class and the objects of the class are sales data, sales manager, and secretary.
Ruby is a true object-oriented programming language. Everything in ruby is an object. All objects contain data, attributes, properties and methods.
How to create a class? Thats easy. Just write the keyword class
. Followed by a capitalized Name, that we want to give it. Also it has to be singular.
class Cat end
That was it, we had created a new class of Cat. So what now?
Everything we call Cat.new
, we create a new cat object or an instance from the Cat class factory. Each cat instance is different from one another. No two instances are the same. By adding methods to a class, we are providing addition attributes/information to the Cat class.
class Cat
attr_accessor :name def initialize (name)
@name = name
end def sound
puts "meow"
end def jump
skill = "jump"
puts "the cat learned how to #{skill}."
end def sleep
puts "ZZZzzz"
endend
We now given the Cat class 4 new methods + 2 methods from the macro, the attr_accessor, which is made up of attr_writer and attr_reader. Now every time we create a new cat instance, it will have a name, can be renamed, able to meow, able to learn how to jump and knows how to sleep.
The initialize method is a special method that it will call itself once a new instance is create. It can take in 0 arguments if the parameter is not given. In our example, 1 parameter is given.
@name is an instance variable. By attaching a @ in from of a variable it becomes an instance variable. So what is the different between a variable and an instance variable? Scope. A normal variable is only visible inside of a method in which it was created. Instance variable is that, they are visible everywhere in the object.
There is also a class variable @@class_var
which is like a global variable $global_var
but only within the class.
Our new cat instance…
cat1 = Cat.new("Charmy")
cat1.name ==> "Charmy
cat1.sound ===> "meow"
cat1.jump ===> "the cat learned how to jump."
cat1.sleep ===> "ZZZzzz"