DEV Community

Discussion on: Explain Ruby's define_method like I'm five

Collapse
 
rhymes profile image
rhymes

@mudasobwa thanks for the addition!

Do you agree how weird is that syntax though?

I have to call extend on an object but then suddenly have to create a new Module and put my method in it.

Ruby's metaprogramming syntax is quite obscure sometimes.

Compare it with Python's, which I find more explicit and clear in this case:

import types

class Player:
  def __init__(self, name):
    self.name = name

  def walk(self):
    print(f"{self.name}: walking")

  def run(self):
    print(f"{self.name}: running")

  def create_method(self, name, method):
    # set an attribute on this istance, with a name and the given method
    setattr(self, name, types.MethodType(method, self))


mario = Player("mario")
luigi = Player("luigi")

mario.walk()
luigi.run()

def fly(self):
  print(f"{self.name}: fly like an eagle!")
mario.create_method('fly', fly)

mario.fly()

luigi.fly()

the output:

mario: walking
luigi: running
mario: fly like an eagle!
Traceback (most recent call last):
  File "t.py", line 29, in <module>
    luigi.fly()
AttributeError: 'Player' object has no attribute 'fly'