Thursday, January 10

Ruby Classes - 1

Ever since the languages have come up with approach of problem centric not just the system centric, we have been hearing about these Objects. Since our daily life is around, with objects this would ease our understanding the problems, solving the problems.
As we know Ruby is pure object oriented language (no datatypes, all are treated as objects), and the Object Oriented paradigm very well fits with Ruby too!

* Abstraction
* Encapsulation
* Inheritance
* Polymorphism

So how the classes come into picture ?
Well a category(group) of objects like (similar) is called a class
Classes hold the properties, characteristics and the actions that are done by objects. This acts as constructor to create more such objects. And we all know that the objects in the real world communicate with each other, similarly here we have the actions/methods doing the job of communication across objects of different classes.

In ruby the class will look like this:

Download Examples on Classes
Example 1: Classes.

class ClassOne

def do_something

puts ("I am displayed")

end


end



c1 = ClassOne.new
c1.do_something


# Observe:
# --> The class starts with "class" (all lower case) keyword and concludes with "end" keyword.
# --> The class name starts with Capital/Multi-word written using CamelCase (ClassOne)
# --> The (.new) is the method that would create multiple copies of objects belongs to a class.
# --> Once the object is created(c1), it gain access to all the methods(dosomething) defined within the class.
# --> The method name starts with lowercase (just convention) and multi-word separated with 'underscore'.

Download Examples on Classes
Example 2: Shows passing parameters to methods.

# Class is like a blueprint from which individual objects are constructed.
# Methods/Definitions/Actions are the means of communication between the objects.

class ClassOne

def do_something(doing)
puts ("I am #{doing}")
end

def someone

puts "I am not public but private"
end

end


c1 = ClassOne.new
c1.do_something("singing")
c1.do_something("listening")
c1.someone

# Observe:
# Passing parameters across objects to actions
# --> The class starts with "class" (all lower case) keyword and "end" is the end of the class.
# --> The class name starts with Capital/Multi-word written using camelcase
# --> The (.new) is one of the methods that would create multiple copies of objects belongs to a class.
# --> Once the object is created(c1), it gain access to all the methods(dosomething) defined within the class.
# --> The method name starts with lowercase (just convention) and multi-word separated with 'underscore'.

Download Examples on Classes

No comments: