DEV Community

loading...

Discussion on: Ruby: class methods vs. instance methods

Collapse
citizen428 profile image
Michael Kohl

The nice thing about Ruby's object model is that class methods are really nothing special: SayHello itself is an instance of class Class and from_the_class is a singleton method defined on this instance (as opposed to instance methods of Class that all instances share):

SayHello.singleton_methods
#=> [:from_the_class]
Enter fullscreen mode Exit fullscreen mode

Conceptually this is the same as defining a singleton method on any other object:

s = 'dev.to'

def s.yell
  'DEV.TO'
end

s.yell
#=> "DEV.TO"

s.singleton_methods
#=> [:yell]

# alternatively
# class << s
#   def s.yell
#     'DEV.TO'
#   end
# end
Enter fullscreen mode Exit fullscreen mode
Collapse
adamlombard profile image
Adam Lombard (he/him) Author

Thanks for the deeper dive on that, Michael!

Collapse
mth0158 profile image
Mathieu EUSTACHY

Thanks for this @citizen428 !