[Rails] class and self in Ruby

Tags
Rails
Engineering
Created
Oct 13, 2023 03:40 AM
Edited
Oct 12, 2023
Description
class and self in Ruby

Class in Ruby

Inheritance

class Human
end

class Man < Human
end

class Woman < Human
end

Super

  • super is the same method from the parent class.
class Animal
  def speak
    "Hello!"
  end
end

class GoodDog < Animal
  def speak
    super + " from GoodDog class"
  end
end

sparky = GoodDog.new
sparky.speak        # => "Hello! from GoodDog class"
 
  • super will take the arguments directly
class Animal
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

class GoodDog < Animal
  def initialize(color)
    super
    @color = color
  end
end

bruno = GoodDog.new("brown")        # => #<GoodDog:0x007fb40b1e6718 @color="brown", @name="brown">



class BadDog < Animal
  def initialize(age, name)
    super(name)
    @age = age
  end
end

BadDog.new(2, "bear")        # => #<BadDog:0x007fb40b2beb68 @age=2, @name="bear">

self

Ruby sets self to this new instance of Class.

What is class << self?

It is a way to create class methods.

What is def self.function_name?

Pretty much like the previous one as to create class methods.

Related Articles