What is metaprogramming in Ruby?

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 decision
class Decision
# create method agree
def agree
puts "Say Yes!!"
end
end
# calling
puts 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 disagree
def disagree
puts "NOOOO!"
end
end

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 agree
Decision.new.agree
=> Say Yes!!
# display disagree
Decision.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

Copyright ©2025 Educative, Inc. All rights reserved