DEV Community

Cover image for Object Oriented Concept In Ruby
Madhu Sudhan Subedi
Madhu Sudhan Subedi

Posted on

Object Oriented Concept In Ruby

Object oriented concept is one of the popular concept in programming. I am learning how Object Oriented Concept Implemented in Ruby, So In this post I will write about it.

1. Almost Everything is Object

  # a is an object 
  # a.object_id gives the identifier
  a = 10

  # similarly b is also object
  b = "Hello World !"
Enter fullscreen mode Exit fullscreen mode

Arrays are object, Class are Object, Modules are object, Range is also object, Blocks of code can be Object, nil is also object which represents nothingness and almost everything is object in ruby.

2. Classes

Syntax for writing class in ruby is straight forward, just you write keyword class and class name. Method inside class is in small latter and snake case syntax is more preferred. Instance variable of class in ruby can be started with @ symbol.

And initilize is the special function of class which is automatically called when object created. To create the Object of the class we can use the ClassName.new syntax. One of the simple example is as follows.

require 'date'

class User
  def initialize(date_of_birth)
    days_since_birth = Date.today - Date.parse(date_of_birth)
    @age = days_since_birth / 365
  end
  def is_kid?
    @age <= 18
  end
end

john = User.new("2006-02-12")
puts john.is_kid? # Returns False
Enter fullscreen mode Exit fullscreen mode

Initilize method is automatically called when object is created, and Above code snippet is all about creation of object of User class. age is the class variable.

3. Methods

Methods are pretty fundamental to ruby, method just start by the def symbol, method name with no or more parameters.

    def another_method(first_arg, last_arg)
        "You passed in #{first_arg} and #{second_arg}"
    end
Enter fullscreen mode Exit fullscreen mode

It is possible to create method name by capital letter, But please do not do this. So always write method lower case latter connected by the underscore.

    def ThisIsPossible
        # Please do not do this
    end
Enter fullscreen mode Exit fullscreen mode

Methods which return true or false (Boolean Value) always ends with question mark.

    def is_not_boy?
      @gender != 'boy'
    end
Enter fullscreen mode Exit fullscreen mode

Exclamation mark ! at the end of the method in ruby mean lookout, that means original reference value of the property is also changed so be aware of it. for example

    message = "Hello World"
    message.downcase! # This change message value to 'hello world'
Enter fullscreen mode Exit fullscreen mode

We can define the optional argument in ruby is also possible, optional argument should be always last argument in the method.

    def greet(name, informal = false)
      if informal
        "hi #{name}"
      end
      else
        "Hello #{name}"
      end      
    end
Enter fullscreen mode Exit fullscreen mode

Let's say there is three argument and two of the argument are optional. we do not need to send the default value but if third argument is different than default value of argument then we should pass all the three argument during method call right? lets clear from the example

    def greet(name, informal = false, shout = false)
      greeting = if informal then "hi" else "hello" end
      message = "#{greeting} #{name}"
      if shout
        message.upcase
      else
        message
      end
    end

    greet("John", false, true)
Enter fullscreen mode Exit fullscreen mode

To fix this we can do like this way ! This is much clearer way to pass the arguments in ruby methods.

    def greet(name, informal: false, shout: false)
      greeting = if informal then "hi" else "hello" end
      message = "#{greeting} #{name}"
      if shout
        message.upcase
      else
        message
      end
    end

    greet("John", shout: true)
Enter fullscreen mode Exit fullscreen mode

Normally we do not need to return the value in methods, last value of method is automatically return by the method. But sometime we should return if any conditions then we can return value by using return keyword like this.

    class MyClass
      def odd_or_even(num)
        return unless num.respond_to?(:odd?)
        if num.odd? then  "odd" else "even" end
      end
    end

    MyClass.new.odd_or_even(3)
Enter fullscreen mode Exit fullscreen mode

4. Inheritance

Ruby only support single inheritance that means every class in ruby has exactly one super class. We can specify superclass by writing the '<' sign followed by the name of superclass. Class inherit methods from superclass.

    class User
      attr_reder :name
      def initilize(name)
        @name = name
      end    
    end

    # child class of User class
    class Admin < User
      def is_admin
        true
      end
    end

    user = Admin.new("Madhu Sudhan")
    user.name # will results 'Madhu Sudhan'
    user.is_admin? # will return true
Enter fullscreen mode Exit fullscreen mode

Here is the example how one class contains exactly one superclass see the follwing example

    Admin.superclass
    => User
    User.superclass
    => Object
    Object.superclass
    => BasicObject
    BasicObject.superclass
    => nil
Enter fullscreen mode Exit fullscreen mode

5. Modules

Modules in ruby is really just a collection of methods and class is also a special type of module. We can define modules same ways a class.

require 'date'

module Employee
  attr_accessor :start_date

  def employment_length
    days = Date.today - start_date.to_date
    "#{days.to_i} days"
  end
end

class User
  include Employee
end

u = User.new
u.start_date = Date.today - 365
puts u.employment_length
Enter fullscreen mode Exit fullscreen mode

Extend is another way to use module and is much more interesting, before we are using include keyword that the module define in the class, but we can also use the extend keyword tell the method to single instance of class,

require 'date'

module Employee
  attr_accessor :start_date

  def employment_length
    days = Date.today - start_date.to_date
    "#{days.to_i} days"
  end
end

class User
end

u = User.new
u.extend(Employee)
u.start_date = Date.today - 365
puts u.employment_length
Enter fullscreen mode Exit fullscreen mode

6. Constants

Constants in ruby a pretty much like constant in any other language, it violets the mutation of the value. Look like variable but start with capital letter. It is a convention that all the letter of constant should be uppercase.

    PI = 3.14 # is good

    Pi = 3.14 # is possible but not do it
Enter fullscreen mode Exit fullscreen mode

Using the constants in class and Modules can be access like this way

    module Geometry
      PI = 3.14
    end

    class Circle
      PI = 3.142
    end

    puts Geometry::PI == Circle::PI # false

Enter fullscreen mode Exit fullscreen mode

Conclusion

It's really interesting to learn ruby programming language and it's easy too.

Top comments (0)