Menu

1 / 6

In Ruby, Objects Don't Have Methods. How Method Lookup Actually Works.

DEV Community: ruby·S M Tahosin·about 23 hours ago
#eSPmzUkJ
#devtoruby#devto#dev#singleton_class#ruby
Reading 0:00
15s threshold

Ask almost any developer how object-oriented programming works, and they will describe the same textbook picture: an object bundles data and methods together into a single unit.

In Ruby, you hear this idea reinforced constantly under the slogan: "Everything is an object."

You create a string, call .upcase on it, and it feels completely natural to assume that the string object owns that method. You create a user object, call .save , and assume .save lives inside your user.

Except that is not how Ruby works at all.

In Ruby, objects contain zero methods .

If you inspect an instance down at the C source code level in CRuby (MRI), you discover something surprising: an object stores its instance variables, a set of internal flags, and a pointer to another structure. It does not contain a single line of method code, nor does it contain a method table.

Where do methods actually live? How does Ruby know what to execute when you type user.greet ?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.