Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
metaprogramming

What is metaprogramming in Ruby?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

ruby
metaprogramming
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring