0

I am looking for a good analogy to help the concept of a method in ruby stick in my head. When I truly understand a concept, an image flashes in my mind that relates something physical to the abstract concepts I am trying to learn.

For example, someone explained the concept of a variable to me in the following way:

A variable is like a box you can put things in. The name of the variable is like taking a sharpie and writing a word, like "forks" on the side of the box. Picking a good name is important. You can stick anything in the box, but if you write 'forks' on the side of the box, you would expect forks to be in the box. You can put anything in the box, then carry it around to various people, and tell them "there are forks in this box." When they need a fork, they go to the fork box and get out a fork.

That's the sort of physical, image-based, concrete analogy I am looking for for a ruby method.

Right now most definitions I have found are useless to me. For example, at turtorialspoint, the first result for the google search 'what is a ruby method,' has the folowing definition.

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

Let me give you an example of why this definitions is useless to me. I'm going to replace every word and concept in this definition that I don't understand with the word 'blah.'

Ruby blah are very similar to blah in any other programming language. Ruby blah are used to blah one or more blah blah into a single blah.

In summary, can I get a good, physical analogy for the concept of a method in ruby?

Tara Roys
  • 113
  • 2
  • Do you really need an analogy? Is it so hard to understand these things? –  Jan 25 '14 at 09:14
  • Short answer: yes. Longer answer: without analogies, it takes me months to grok a concept. With analogies, it takes minutes. – Tara Roys Jan 25 '14 at 16:40
  • That seems SO strange to me but I believe it. Was mine helpful at all (since I can't grok why analogies are helpful lol) –  Jan 25 '14 at 22:46

6 Answers6

3

On the similar level as your variable boxes - as a distant analogy - these methods can be seen as recipes. e.g:

to make spaghetti you:

  • boil salted water
  • throw in the spaghetti
  • check repeatedly if spaghetti are ready
  • take out the spaghetti

in pseudocode:

def make_spaghetti()
    boil_salted_water()
    while not ready()
        wait(30)
    take_out()

You have a name and some instructions, and - as with the boxes - the name of the recipe should give a precise idea of what is done.
Note how the instructions like boil_salted_water are smaller recipes themselves (take a pot, pour in some water, etc.).

ps: now if you ask for the context of the recipe like who's the cook, the kitchen, ingredients, etc, refer to @9000's answer.

kr1
  • 1,053
  • 7
  • 13
1

I DON'T use analogies but if I were it'd be like this (non ruby specific)

A variable is post it note. It can have values of any kind and usually theres a type written or associated with the post it note. Also post it notes may be different sizes (tiny such as byte and extra large for double and decimal cause you know its a lot of digits to write down).

An array is box of post it notes. The box may have 0 to many notes and you can put more into it or take some out

An interface is a cable adapter. Kind of like a micro<->usb cable. You computer, power adapter or another device uses a USB slot but the other end you are using something else (your phone which uses a micro usb).

A class is a device like your phone. It does stuff and has an interfaces to it. Like the touchscreen or micro usb (two different interfaces, one for human other for machine). Or a memory stick if you want something different.

A method is a recipe. It tells you what it needs (ingredients) and what it produces (other ingredients or a muffin).

You MAY have a post-it note refer to a recipe

A virtual method is an advance recipe. You can change the cake or muffin it creates by adding frosting or even changing an ingredient (carrot instead of chocolate).

A class with a base class is a hacked phone. It does more and things it wasn't meant to do. Or a the 32x for sega genesis. It makes it do way more then it should be able to do (it has its own processing chip)

A Tuple is a shish kabob. It can have really as many things as it wants and way different types (meat, pepper, fruits, cheese ANYTHING)

IDK if you want any more. These were pretty fun to do and many of these I havent thought until now and were easy to think up.

  • These are great! The reason I like analogies is that they give me a mental model to help remember things. I like the interface analogy, because the fact that it's like a cable means that I can reason several things about it. For example, a cable adapter implies that you have two things talking to eachother, something on one side of the adapter and something on the other side. It also implies that they don't quite speak each other's language so an interface is a way of 'plugging' to different things in to each other. With that mental model, I have a chance of remembering what it is. – Tara Roys Jan 26 '14 at 22:03
1

You can use a microwave manually, by setting the time you want to use it for. You might want to melt butter for 15 seconds, so you push 1, 5, and "Start".

But the microwave also comes with convenient buttons you can use, like defrost, popcorn, rice, etc. If you think of them as ruby methods, it would be:

food_item.bacon
food_item.defrost
food_item.rice

You don't have to put the time manually. The microwave already knows what to because someone wrote those methods:

def bacon
    # Push the buttons to cook bacon, 8:00 minutes
    push 8
    push 0
    push 0
    push "Start"
end

If you melt butter often, you could add a convenient button/method:

def butter
    # Push the buttons to melt butter, 15 seconds
    push 1
    push 5
    push "Start"
end

And then you could just push the butter button, or call it in your code:

food_item.butter

... now I'm hungry :/

June
  • 11
  • 2
0

One typical way to explain methods, interfaces, and polymorphism is to take several similar real-world objects as an example.

For instance, take a hen, a duck, and a turkey.

They all implement an interface for moving over a solid surface that consists of method walk(direction). This method is implemented slightly differently in each (you can tell one gait from another) but consistently.

They all implement an interface for producing sounds, that consists of method that we'd call quack(). Again, it has distinctly different implementations in all three.

Unlike two others, the duck implements another, aquatic interface, by having methods swim(depth) and dive. An attempt to call either of these on the hen or the turkey will end up in an infuriated and loud error message, or even in an abnormal termination of them.

One more important interface is aerial, consisting of take_off, fly, and land methods. Support of this interface is uneven. While the duck and the turkey reasonably implement all three, the hen has mere stub implementations of take_off and land and lacks an implementation of fly. The latter is a regression in implementation, because hen's ancestors have a well-working implementation. But since nobody seems to ever invoke hen.fly(), it is not even planned to be fixed. On the other hand, duck has an enhanced implementation of land(surface) that accepts both land and water objects as the argument.

In languages with a static class hierarchy a bird should be formally certified as a duck to function as one. Ruby implements duck typing, allowing a bird that quacks like a duck and walks like a duck to be accepted as a duck.

Note that the above only applies to situations where locomotion and sound production is involved. In other contexts, e.g. roasting, a bird that does not implement correct cooking and tasting interfaces could make a subsequent operation of eating fail unexpectedly. Ruby lacks built-in means to check for this beforehand, but has enough flexibility to implement such a check manually when required, at an additional cost.

It's important to notice that all methods has an implicit parameter, self. There's no way to quack abstractly, one needs an instance of a e.g. duck; duck's self defines concrete details of method invocation. The whole point of objects (that is, of self) is to hold some state. For instance, duck's hunger level is a part of the duck's state. The implementation of quack consults the hunger value of self, and increases volume accordingly.

Importance of internal state can be seen on methods like get_mass. Various other methods, like peck, drink, or excrete change the summary mass. get_mass is shared by all objects in the universe. It is likely to have only one canonical implementation, inherited by all objects, including our three birds. Different implementations of quack and walk by different birds is an example of implementation polymorphism.

Hope this helps :)

9000
  • 24,162
  • 4
  • 51
  • 79
0

From another perspective:

A method is an action you can ask something (usually stored in a variable) to perform for you.

For instance, you could ask a whiteboard to erase itself. It doesn't matter how it's done, it might be a fancy electronic whiteboard with self erasing capabilities, or when you push the erase button it calls downstairs and an someone comes up and erases the whiteboard for you. But the result is what matters: you have a dirty whiteboard, when you call the erase method it gets cleaned.

Similarly, you could have a microwave.cook( meal, duration, power ) method - where you give the microwave your meal, set a duration and power, and press the cook button. The result (the return value of the method) is a cooked meal (or it could mutate the meal object you're passing to make it cooked).

You have complex methods (shuttle.go_to_the_moon), and simple methods (meal.are_you_cooked?) - that don't do anything, but just ask the object its state. The implementation of a method is like the recipe from the perspective of the object: as a whiteboard, to erase myself, I need to issue a call to the cleaning department and tell them I need to be cleaned. If you're writing the method, you obviously need to figure it out. But if you're just calling it, you don't need to care.

(I don't like the recipe analogy much though, as it's code centric, and when you design software code doesn't matter as much as how you call it).

ptyx
  • 5,851
  • 2
  • 22
  • 21
0

An object is an entity with identity, state and behaviour.

Make an analogy with. say. living organisms.

Identity is pretty easy - two organism are same when they are equal (in state and behaviour), but also occupy the same space (eg. it is the same dog, just two people call him with two different names).

State are variables, that is, physical attributes. Skin colour, eye colour, health ... those are all parts of the state; when simulated in a program, it will be variables.

Behaviour is, well, how an object changes its own or external state when reacting to a stimulusl. These are methods. Lots of instances of the same class (lots of dogs with the same breed) share the same basic behaviour based on their state (the methods are defined in the class; while attributes are defined in an instance; method manipulate instance variables). Plus there is individual pattern of behaviour (singleton class).

herby
  • 2,734
  • 1
  • 18
  • 25