 I'm going to tell you a story today, you've come to hear about the case of the missing method. But before I get started I've got a question for you. Do you have a side gig? You know, something that brings in a little extra each month. I do. Dyma, rydyn ni'n ymweld y cysylltu yma i gael y tîm yn y bank. Fy rydyn ni, rydyn ni'n ymweld y cyfrifredinol. A mae wedi'i cyfrifredinol? Rybyrch. Nid yw John Fefft yng Nghymru'r Llangwys. A mae ydych chi'n gweithio i'r cyfrifredinol? Rydyn ni'n ei ddau'r rheidio'r llunion mynd a cwrsafodd a cael y cyfnodd i amser panfio'r adroddau rhywbeth yn y gyrhaf a'r adroddau'r gyrhaf. Ac rwy'n gweithio i gael bod yn dod i'r cyflog. Ond rwy'n gweithio'n gweithio'r gyrhaf ar y rai ddweud. Rwy'n gweithio'n gweithio'r adroddau. Byddwn i'r adroddau'r ddweud, D, ond hynny. A byddwn i gweithio'r adroddau'r adroddau? Wel, rydyn ni'n gofio'r gweithio'r adroddau'r gweithio'r adroddau. Ac oeddwn i'n gweithio i chi'n gweithio'r cysyllt arall y gweithio'r methu. Cepta 1. Felly, rydyn ni'n gweithio'r gweithio ar y gweithio. Felly, rydyn ni'n gweithio'r gweithio, maen nhw'n gweithio'r gweithio. Yn y ddweud o'r ddweud, a mae'n Mike. A rydyn ni'n gweithio'n gweithio'r gweithio. Rydyn ni'n gweithio'r Mike. Felly, rydyn ni'n gweithio'r gweithio'r gweithio hon. Yn y ddweud fwyf lovelya, gan thoseiau yn memnwys iawn. Rydyn ni'n ddweud y drafotod dros arall, ac rynnno'r gweithio'r tystr y peithio. Rydyn ni'n gofio y panodd cyroedd y sort beatenidio y prysg��ith yma neu rydyn ni'n gwneud resist ofionlu. Felly ni'n caelكلu'r gerbyn eich eithaf universell intriguing pa Hearley'r Gathenardiau i'r seniolurellna piynhaelach y bob yn rhas sy'n左右 ac rhaAT mwyn gwan. ac mae'r gweithio'r gweithio i'r gweithio ar y gweithio'r llunio'r llunio. Ielodd yn gweithio, a y dyfodol yn ymgyrch genni. Dwi'n ddweud i genni. Aeth oedd yma yma yw 27 oed, mae'r genniol yn y rwybiad yn ymgyrch, a mae'n gofio'r rhaid i'r cyflwyno. Mae'n gofio'r amser, Mike's best friend a housemate. Nid ydy'r gwybod iawn i ddim yn yw'r gwnaeth a'r adwy cream Llywodraethol yn cael ei wneud mewn gweld i'r gyrwleddol, ac yn ystod o ensi Gweinidol yn gweithio'n gweld. Dyna mae'r rhaglen o'r cyfridog bryd o'r fforddau i gadasig i ddifion ar gyfer gwahodd gofod i gwestiyno bwysig o gyfer gydweithio'r diolio'r bair inni. Mae'r melys i'r braff honno. Dyna ajw, mae'r rhaglen o'r fforddau ar gyfer gwahanol, ac mae'n gweithio'r bywysau sydd wedi gynnig y byddai'r bywysau. A hynny'n ymwysig yma, mae'n ymddangos ymddangos. A mae'n cyfnodd ar hyn o'r bywysau gyda Jenny. A dyma'r ddweud y gallu bod yn ymddangos i mi. Mae'n gweithio'n gweithio yn gweithio'n gweithio. Ond Jenny'n byw'n gweithio i'r bywysau, yn gweithio'n gweithio'n gynghwilio, ac mae'n gweithio'n gweithio'n gweithio. Mae'n gweithio ddau i chi'n frefwm, a dwi'n ddau'n ddod i gyd yn dod i'r ddod i fynd i gyd. Ond yn digwydd i chi'n gynhyrchu yng nghymru. Mae'n gweithio'n gwybod o'r ddau ar hyn o'r ddiadau'r ei wneud a chi'n gwybod i gyllidol gael gennu i'r ddod i gyd yn ddod i ni'n gwybod, ac mae'n gwybod i gyd yn ddiad i chi'n gyfrifio ac mae'n gwybod i'r ddod i chi'n ddod i neud. Mae gwneud gennu i gyd yn ddod i gyd yn gwybod i gyrwch. I asked him to walk me through them. So Jenny had these boxes to represent the concept of a ruby object. And all of these objects had a label called class. And this acted as a reference to the parent class of the object in question. So some of these objects were instance objects. And the class label for these referred to another ruby object of type class. Class objects also had their own class label. And all objects of type class also had a methods label. And this pointed to a table of all the methods that instances of that class could call. And then Jenny had written, any class you define is an instance of a class object called class. So if we were to write class cake in our code, we're creating a class object named cake, it's an instance of another class object and the name of that object is class. So all classes are of type class with a capital C. And then Jenny had this code in her notes. So it was class cake and there were two methods. There was one instance method called tasty, which returned true if the flavour of the cake in question was carrot. So I immediately knew Jenny was smart, she was clever. And then there was a class method called edible which always returned true. Okay. Then she wrote, imagine we had a cake instance called carrot. So she had carrot equals cake dot mew. Then this is what the method look up chain would look like. So she had one of her boxes and she'd labelled it carrot. It had a class label. It pointed to another one of the ruby object boxes and it was called cake. That had its own class label. It also had a methods label which pointed to a table and there was a single entry, the tasty method. Because all instances of cake could call tasty. And then the class label for the cake object pointed to another object labelled class with a capital C. And it had a methods label and that pointed to a table also with a single entry called edible. And then Jenny had written, a method definition always comes from an object's class. And at this point Mike shook his head with frustration. It cannot be that the edible method lives on the parent class for all classes, he said. Can I show you something here? Can I jump on your computer? I said, okay, so he goes over to my desk, opens up terminal, enters pry and he loads in this cake class from Jenny's notes. So then he shows that the class of cake is indeed class and then he searches all of the instance methods for edible in class. What a mystery. I am stumped at this point and I'm just not sure how to proceed with this one. But if anyone can tackle a challenge like this, it's D. And besides, this meant a lot to Mike. He was prepared to pay me handsomly. And so I agreed to take on the case. Chapter two, ever heard of Google? Or if you care about your privacy or you don't like people on me spying on you, maybe you use duck, duck, go. Well, when I'm D, I don't believe in these tools. No, I don't trust them. And it's no coincidence that with this approach, I've become the best Ruby PI that industry has to offer. And so what did I have? Books, books and more books. And I spent a whole day quickly skimming a load of books, but I couldn't find any useful information. So I thought, well, why don't I form a hypothesis and go from there? So I said, okay, the edible method, while not on the cake object, it must be somewhere in the ancestry tree. So what's the ancestry tree? Well, it shows all of the classes and modules that a class inherits from. So all the possible places that a method could come from when you call a method on an object. And I thought, well, how do I search this ancestry tree? So I made a method called where. And it took two parameters, an object and a method. And that's the method that you're trying to search for in relation to the object. And I looked through the ancestors of the object's class to try and find the class where the instance methods of that class and only that class included the method I was looking for. So I thought, let me just check that this method's working. So I created an instance of cake. And I said, let me find the tasty method on this instance carrot. And if it's working, it should be on cake. Great. Now it's time to find the edible method. It has to be somewhere in the ancestry tree. What? Nowhere? At all? God, what a mystery. And at this point, I am confused. And I think, okay, it's time for some fresh air. It's time for a change of scenery. And so I decide to go to my favourite co-working space. And here I feel at home. Because I'm surrounded by people hacking away. And I quickly settle down at one desk. Given my naturally inquisitive nature, my eyes couldn't help but stray to the screen of the guy next to me. And he was playing around with this thing called object space in IRB. And I asked him, I said, what's that? That looks interesting. And he said, well, it's a way that you can interact with all of the live objects within a Ruby session. So if you were to type in object space dot count objects and pass in the symbol t class, you can count all of the live class objects that you have in a Ruby session. So I thought, okay, it's probably time for a break. Let me have a play by myself in IRB. So I went into IRB and I did what the guy had shown me. I counted up all the class objects. 936. So I thought, okay, let me create a class and see that that number goes up to 937. 938. What? Okay, let me try that again. 940. What a mystery. But I don't have too much time to think about this because just then my phone rings and it's my friend wondering where I am. So you see, I completely forgotten that I'd agreed to go to this tech lecture with her and I was anxious that I really didn't have much time to solve Mike's case. But I'd been cancelling a lot on this friend lately, putting my investigative duties first. And I thought that maybe on this occasion I should make a little bit of time for her. So I rushed out of the door. Chapter three. So I arrived just in time for the beginning of the lecture and it was about a language called small talk. I wasn't interested at all. I mean I only have space in my heart for Ruby. But as I said, I was there for my friends. The lecture was talking about how small talk had been born in the 1970s and it had led to the creation of object-oriented programming. But it wasn't long before I couldn't concentrate. I couldn't stop thinking about my play with object space. Each time I'd been creating one class but yet two objects were being created. Pay attention, my friend said. So I looked up to see the lecturer asking the room what is the class of a class in small talk? And she had this code on the screen and I hadn't been following but I could see that she'd printed out this polygon object and then she'd asked the system that she was interacting with well what's the class of the polygon object and it had returned polygon class. And then she typed in polygon class class and it printed out meta class. And she said the class of a class in small talk is called a meta class. And then she went on to say that all languages that have been inspired by small talk have their own concept of meta classes. And that included Objective C, Java, Python, Ruby, Ruby. Oh, something clicked. One class, two objects. So I made my apologies to my soon to be no longer friend and I rushed out of the door and ran home and I thought okay, let me try my luck. Okay, of course that was going to be too easy. So I said well let me look at all the methods that exist on cake. So I found this list rather overwhelming so I thought how can I filter it down? Let me look at all the methods that include the word class. Okay, so this list was a lot more manageable and two methods stuck out for me. One was super class and the other one was singleton class. Okay, so I thought well let me remind myself that this is an ancestry tree for cake. And I said to myself I know that the edible method already doesn't live on any of these classes or modules. So then I thought well let's see what super class gives me, object. So I immediately knew super class was not what I was looking for, object was in cake classes, ancestors. So that was time to try singleton class. Oh, this was new. I hadn't seen this before. It looked rather strange. I saw three new classes that I hadn't seen before that looked rather different. Very interesting. And so I thought well why don't I go back to my where method and this time rather than searching the ancestors of the objects class why don't I search the ancestors of an object singleton class so I could search through those three new things that I just discovered and then it was time to give it a go. My middle of truth. There was that thing and I thought okay let me just check that what I think is happening is actually happening and in my excitement I forgot how to type but I got there eventually and I confirmed that the edible method lived on cake singleton class. Case closed. Chapter four. So at this point I am delighted. I'm so happy and I'm really excited to share this news with Mike. I also took a moment to wonder whether I should retire because this would prove to be one of the biggest successes of my career and they always say that you should quit when you're ahead. Anyway, I pushed those thoughts aside and I picked up a phone and I gave Mike a call and the phone rings for forever and I'm about to lose hope at reading him when he finally answers and I say hey can I come round, I've solved the case and he's excited, he says of course come round I'll have the notes ready and waiting for you but although the case was solved for Mike I wasn't satisfied because I just discovered a whole new concept in the language that I hadn't heard of before. What are singleton classes? And so instead of going directly to Mike's I took a detour to a friend of mine. She was called Ellen, she was 43 years old a freelance developer and she regularly contributed to the Ruby code base. So I proceeded to tell her all about the case and when I'm done I ask her what are these singleton classes all about? And she says well the hidden classes created internally behind the scenes in Ruby and they're there to hold methods to find only for one particular object so take your instance of carrot of the cake class its singleton class would hold methods specific to carrot only and not to any other instance say if you had one called red velvet or chocolate. So I said okay given that they're working away behind the scenes when does knowing about them become useful? So Ellen fought for a while and then she told me about one of her recent clients they were called budgeting ink and they were a clever artificial intelligence machine learning personal finance tool for small business owners and they were expanding globally and they needed to roll out slightly unique versions of their software for each new city that they entered. Ellen told me how that when she first looked at the code base she was horrified. Different developers had been responsible for each new city and it looked like they were experimenting and trying out a new approach each time whether it was naming things, testing things designing interfaces and so there was a lot of duplication in the code base and sometimes that duplication was very obvious like you could see it directly and sometimes it wasn't so obvious it was hidden beneath the surface but this meant that there was a lot of wasted time on development because the developers were often reinventing the wheel and they were often doing a bad job of it and so there were a lot of bugs some things had been copied hastily some things had been left out and it was really difficult to see what was important so the developers at the company weren't unhappy they had a lot of tiresome, repetitive work and the cognitive load was really high and the product owner was also unhappy because delivery was either very slow or things were spun out quickly and they were bug ridden so Ellen wasn't quite sure what to do and then she said well I decided to create a DSL, a domain specific language and she asked me if I knew what she was talking about it's a mystery Ellen, you're going to have to explain so she said well let me show you what a basic version is she beckoned me over to her computer and she opened up pry and she input this class so it was called city instance it had a class method called construct which took a block it then set up a variable called city which called up to initialize via the new keyword then we called instance of violent city passing in the block that we passed into the construct method and then we returned the city object there was an attribute reader called taxes we then had an initialize method which set up an instance variable called taxes as an empty array and then we had a method called tax which took an argument called name and that pushed the name of that tax into the taxes collection and that was time to give it a go so Ellen created a city instance called New York and she added a couple of taxes and then she printed out the taxes in New York and so she said there we have it that is a very simple DSL and now we can quickly keep spinning up these lightweight city objects so imagine if we had other properties though like a list of banks in a city or finance schemes and imagine if we had more information on each of these properties so maybe with the taxes rather than just the name we had some information about the threshold and the different rates so using this simple framework as a starting point it's not hard to extend the city instance class to create incrementally more complex city objects well imagine taking this to the next level imagine interacting with the city instance class in the same way on the command line but instead of just creating variables in our price session we're spinning up new subclasses of city and other related models for each tax scheme bank that we list so Ellen explains that this was the sort of thing that she had created for budgeting Inc a DSL that allows for quick easy scaffolding of each new city subclass and any other related classes so she said ok I've shown you how you spin up identical city instances that have different names and different taxes but what about if we had one city that had a quirk so she asked me to think of a place in the UK and I suggested Bath since that was the scene of my first ever case so she said ok let's take Bath and let's add a tax and then she said can you think of something that makes people in the UK really unhappy and she didn't like my suggestion she thought it was a bit too controversial so she said well let's focus on the fact that it rains all the time in the UK and let's say the local government feels sorry for people and so they clear all the taxes when it rains so we looked at Bath's taxes and then it rains so the government said we'll call a rainy day amnesty and then we look at the taxes again no afternoon tea tax now remember our friends in New York Ellen said well they've heard about this rainy day amnesty and they want some as well and so it rains in New York and the government tries to call one but no undefined method of rainy day amnesty for city incidents and then there were these interesting characters after it and Ellen said well what are these interesting characters let me show you something and I saw that when she called Singleton class on New York the exact same class object was returned and so Ellen said when we enter the realm of DSLs and we're calling methods like instance of AL what we're doing is we're leveraging the existence of singleton classes because what instance of AL does is it stores any method declaration that we pass into the class via the block argument on an object singleton class so hold on to that thought said Ellen I just want to take a step back to the high level for one second so she says that by creating a DSL like this for budgeting Inc she enabled the developers to spin up each new city instance effortlessly so she explains how she had like abstracted away the key similarities between any city so now the developers had a frictionless way via the command line of spinning up the foundation that they needed and the code was way better maintained because all of the scaffolding had been tested once and tested by Ellen so now the developers didn't have to worry about it they didn't have to touch it unless they changed that code instead they could now focus on the interesting parts the customization that was required for each new city the scope was much more refined so now the developers were happy because interacting with the system was a joy it was easier to have a high level overview of the whole domain purely just by looking at the documentation for the DSL and the product owner was happy also because there were far fewer bugs delivery was much faster and she could also speak in the same language as the developers just by expressing new requirements in the terminology of the DSL and now let's go back to singleton classes of Ellen so why is knowing about them useful well one of the main reasons I was able to complete this project to a high standard said Ellen was because I understood exactly where I was defining methods at any given time she said that once you enter the realm of dynamically creating classes and methods on singletons like we did well and as you saw in your investigation the class hierarchy and method lookup gets far more interesting and so you might be getting error messages and you need to be able to spot where singleton methods and classes are involved and where they're hiding because it can save you from a lot of headache but beware Ellen said I've been going on and on about DSLs but they're not the answer to everything if you have perhaps complex repeated business rules and maybe you need to customise behaviour in specific instances then you can consider DSLs as an option but even then approach with caution but she said you don't even need to be writing DSLs for it to be beneficial for you to understand how they work so she asked me you're using rails right you're using every day well then you're seeing DSLs every day and she went to the rails guides website and she went to the active record migration section and she said well look these are carried out via DSL when you call create table and you specify what each of the columns are that is a DSL and she also said when you specify how your rails app handle HTTP requests that's also done via DSL and I thought I've always just been doing this by rope I never stopped to think about what was happening behind the scenes every time I typed the resources keyword into my rootsrb file and there's more of these said Ellen so she said that when people talk about rails magic it's not really rails magic it's more a collection of well written DSL and then Ellen looked at me and she said I hope you're TDDing all of the time and I said of course Ellen what do you take me for and she said good because aspect with its describe context its blocks that is all DSLs as well and so with all of these rails and aspects DSLs that you're using every day knowing about singleton classes can help because you might find yourself in the midst of a tricky problem and you can't make head or tail of it particularly if you inherit a code base and so if you're seeing a funny bug to do with methods you never know singleton classes might be the answer and having them as part of your suite of debugging tools can be incredibly useful so I was feeling really leveled up by the end of this conversation and on with this new knowledge I headed over to Mike's but when I arrived I found a Mike who had tears in his eyes he'd obviously been recently crying I looked down and I saw that he had crumpled pieces of paper in his hands he raised his arms towards me offering me the papers they looked exactly the same as the method lookup notes of Jenny's that he brought me the day before so I took the notes from him I looked through them I couldn't see what was wrong they looked exactly the same there was the carrot object with its class label that pointed to a cake object that had its class label it also had its methods label with tasty in there and then the class object for cake pointed to the class object with its methods label which also had the edible entry in there but wait it didn't say class like last time this time it said cake singleton and as Mike saw me notice this difference he fell to his knees and broke down in tears Jenny knew about singleton classes all along he'd gone into her room to find the notes in advance of my arrival and this was the copy of the notes he'd found Jenny was so desperate to secure the job for herself that she set out to intentionally mislead Mike in the hope that he would fail a whole section of the interview and therefore look unprepared I for one was disappointed in myself I had, thank you I had been, I know I had been so focused on the main villain the shady mastermind that I'd failed to spot a villain right under my nose my best friend tried to sabotage me Mike cried and at this point he started wailing again saying he wasn't going to go to the RIP interview tomorrow and I said nonsense you cannot give up now I crouched down next to him I gave him a comforting pat on the shoulder and I said you can do this and I have just the thing to help set you apart from Jenny and he looked up hopeful have you heard of dear selves? I asked him and I proceeded to tell him everything that Ellen had just shared with me and although Mike still looked devastated as I left him I had confidence that I had inspired him with the power of singleton classes that he'd pull himself together and go and secure the RIP internship for himself so it's two months later and I managed to drag myself out of the house to go to a hack night and I'm just standing around milling a bow enjoying the free food and drink when I hear a couple of people whispering in the corner ooh she's Ruby famous one of them says and I look across the room and who do I see? Ellen so I walk over, we catch up and I tell her that I've been reflecting on the case of the missing method I had my takeaways so you know singleton classes they're there to hold methods defined for one particular object and understanding them opens up a whole new world of Ruby because when you're dynamically creating classes and methods on the fly in more complex applications with things like dear selves then it's really useful to understand them but I said to Ellen I still feel as if day to day I can get by ignoring singleton classes so do I really have to care about them at all? not really said Ellen well like you say if you're writing dear selves then definitely yes know what you're doing and they do underpin popular frameworks like I showed you like rail but day to day you can get by ignoring them however she said understanding why singleton classes are there I think is super interesting and empowering think of the Ruby call team they wanted to keep things as straightforward and simple as possible and by simple what I mean is they wanted to minimise special cases can we aim for having one way, one pattern for explaining how anything works in the language they ask themselves how consistent can we get things so let's think about consistency in the realm of Ruby methods well if you think about it all methods in Ruby are defined in only one of two places a normal class object or a singleton class and every method in Ruby is really an instance method and method lookup always starts with a singleton class and class methods don't really have any fundamentally different behaviour to other methods what we call class methods are really instance methods where the objecting question is a class and the method is stored on the class's singleton so yeah singleton classes are invisible but yet they're everywhere they're a fundamental part to how Ruby and its method lookup works so I left the hack night deep in thought Ellen had inspired me to explore more of Ruby behind the scenes cos there was so much here that I didn't know I'd only scratched the surface and while I'd always been a general Ruby PI and I'd been very successful in the field I thought maybe it was time to find a niche so that I could reach that next level