Metaprogramming refers to the idea of writing and editing the code at runtime. The basic idea is that classes can be defined and redefined during run time.
It is used throughout Ruby to implement multiple functionalities.
# create class decisionclass Decision# create method agreedef agreeputs "Say Yes!!"endend# callingputs Decision.new.agree
The code above shows a user-defined class in Ruby. It creates a new class Decision
since the class was not previously defined. During run-time, we can append the following code:
class Decision#create method disagreedef disagreeputs "NOOOO!"endend
Since the class had previously been defined at run-time, the compiler adds the method to the class and no new class is created. Ruby opens the prefined Decision
class and appends the method disagree
in the same class.
# display agreeDecision.new.agree=> Say Yes!!# display disagreeDecision.new.disagree=> NOOOO!
Both the methods can be called at run-time using similar syntax since they refer to methods of the same class, Decision
.
Free Resources