Salut people!
I'm in the process of writing a beginners' introduction to Ruby classes and objects (18th Nov update: it's live!).
While talking with a friend about how classes inherit from their ancestors and the parent Class class, we realized we didn't know how exactly the method lookup works in Ruby.
My first (and wild) guess was: Ruby uses the method(:some_method).owner then check the ancestors' chain. But can't really wrap my head around this.
Anyone around here would like to have a go? 🙏
Oldest comments (4)
Haven't found an answer yet, but the beginners' intro to objects and classes is now live on dev.to @ben 👉 dev.to/mercier_remi/a-beginners-in...
Everything in the world of Ruby is an object. An object is a box of information (data) and actions (methods). If we treated a cat like an object, it would have data like a height or attitude or age. It would also have behaviors like purring, scratching, and sleeping. Because all cats share similar actions and kinds of information, we can put them in an even bigger box called
Cat.Catwith a capital "C" is a class, and it's an object with the types of information and actions that can be found in everycatobject inside it. Since it holds the things that are in common across allcats, eachcatcan just think about the things it knows and does special.Say we have a cat object called
tom. If we wanttomto do something, we have to sendtoma message. We can sendtoma message in Ruby by using a.and the name of the thing we wanttomto do. When we writetom.chasein Ruby, we are writing a message in three parts.tomgets the message,.means we're sending a message, andchaseis the method we're sending.tom.chasemeans, "tom, pleasechase"tomis an object, a box of info and actions. Whentomgets thechasemessage, he'll look inside his box for how tochase. If he can't find any instructions labeledchase, he will look outside his box in the bigCatbox to see if there are any instructions labeledchasethere.Since everything in Ruby is an object, you better believe that
Catis not the biggest box.Catmight be inside another box calledAnimal. Iftomdoesn't find any instructions for how tochaseinCat, he'll check the giantAnimalbox. He will keep looking in bigger and bigger boxes until he either finds some instructions labelledchaseor he gets to the box the size of the Ruby universe—theBasicObjectbox.If
tomcan't find any instructions in theBasicObjectbox, a cry echoes through the Ruby universe, an error is raised, time stops, and the Ruby universe collapses until it's created again.There's also a great StackOverflow thread on the Ruby method lookup path here.
This is crystal clear @levi ! Thank you so much for this. Love the Russian dolls-y metaphor here. 👏
The book "The Well-Grounded Rubyist" has IMHO the best coverage of this I've ever seen. Chapter 4 (and 5) are excellent and well worth the price of the book.
manning.com/books/the-well-grounde...
P.S. No affiliation, just a happy reader (and I got to review the 1st edition)