Canhua's Blog
  • Blogs
  • My GitHub Projects
  • Profile
  • Linkedin
Canhua's Blog

self and class<< in ruby

October 04, 2022

You can use class << self, self.method or className.method for class method

class Project
  def initialize(project_name)
    @project_name = project_name
  end

  def project_name
    "#{@project_name}"
  end

  def self.who
    "Ruby Project class"
  end

  def Project.who2
    "Ruby Project class 2"
  end 

  class << self
    def who3
      "Ruby Project class 3"
    end
  end
end

project = Project.new("Ruby Demo")
puts project.project_name
puts Project.who
puts Project.who2
puts Project.who3

Profile picture

Written by Canhua Li Experienced Full Stack Engineer at Microsoft, proficient in C++, C#, JavaScript, React, AngularJS, Ruby & Rails, and .Net.

  • ← How to test trusted types
  • LLaMa2 local devbox setup and openai API server →
© 2023, Built with Gatsby