How do you define a class method versus an instance method in Ruby?
Last updated
Instance methods are defined with a plain def and operate on instances; class methods are defined on the class itself (commonly def self.name) and are called on the class without an object.
Instance method:
Defined with
def greet; called on an object:obj.greet.Has access to that instance's instance variables.
Class method:
Defined with
def self.create; called on the class:Klass.create.Often used for factories, helpers, or operations not tied to one instance.
Other ways to declare class methods:
class << selfopens the singleton class to group several class methods.Inside the class body,
def self.xworks becauseselfis the class there.
[lang:ruby]
class User
def initialize(name) = @name = name
def greet # instance method
"Hi, #{@name}"
end
def self.anonymous # class method
new("Anonymous")
end
end
User.anonymous.greet # => "Hi, Anonymous"
- https://ruby-doc.org/3.4/syntax/methods_rdoc.html
- https://medium.com/@patrykrogedu/demystifying-rubys-method-types-understanding-instance-methods-and-class-methods-dedc647ef328
- https://thoughtbot.com/blog/a-javascript-developer-s-guide-to-rails-where-does-everything-come-from
- https://dev.to/souzamartin/self-exploration-self-in-class-and-instance-methods-in-ruby-29i1