class Ruby

Estimated reading time: 2 minutes

class

class is a blueprint

  • class keyword
  • CamelCase
class Name
 # some code describing the class behavior
end

yo = Name.new
  • anObject = MyClass.new(parameters)

methods calling

class Name
 def method_1
   puts 'methods 1'
 end
 def method_2
   puts 'methods 2'
 end
 def method_3
   puts 'methods 3'
 end
end

yo = Name.new
yo.method_1
yo.method_2
yo.method_3

Inheritence

class Age
 puts 'age is 21'
end

class Name < Age
  puts 'name is kamal'
end

self

class Integer
  def more
    return self + 1
  end
end
6.more # -> 7

module

  • module, and include keywords
module Swimmable
  def swim
    "I'm swimming!"
  end
end

class Animal; end

class Fish < Animal
  include Swimmable         # mixing in Swimmable module
end

class Mammal < Animal
end

call class inside module

module Mammal
  class Dog
    def speak(sound)
      p "#{sound}"
    end
  end

  class Cat
    def say_name(name)
      p "#{name}"
    end
  end
end
buddy = Mammal::Dog.new
kitty = Mammal::Cat.new
buddy.speak('Arf!')           # => "Arf!"
kitty.say_name('kitty')       # => "kitty"

Inheritance vs Modules

Inheritance Modules
one class multiple class
“is-a” relationship “has-a” relationship

source

ruby