SlideShare a Scribd company logo
Metaprogramming in
Ruby
Nicola Calcavecchia - 24/04/2013
calcavecchia@{elet.polimi.it|gmail.com}
Principles of Programming Languages
1
Metaprogramming
• Writing code that manipulates language constructs at runtime
• In Ruby no distinction:
• Same as “regular” programming
• Enables:
• Code that writes code
• DSLs
• Introspection (e.g., reflection)
2
Introspection
• Allows to get information about objects at runtime
• Methods
• Instance variables
• etc.
class MyClass
! def initialize()
! ! @var1, @var2 = 0, 2
! end
! def my_method
! end
end
m = MyClass.new
m.class
=> MyClass
m.methods
=> # lot of methods ...
m.instance_variables
=> [:@var1, :@var2]
m.public_methods
=> # ...
m.private_methods
=> # ...
m.instance_of? MyClass
=> true
m.instance_of? Object
=> false
m.is_a? MyClass
=> true
m.is_a? Object
=> true
3
Open Classes
• Classes can be “opened” for change
• What about the open/closed principle?
class MyClass
! def a; "method a"; end
end
m = MyClass.new
m.methods - Object.new.methods
=> [:a]
class MyClass
! def b; "method b"; end
end
m.methods - Object.new.methods
=> [:a, :b]
class Numeric
! KILOBYTE = 1024
! def kilobytes
! ! self * KILOBYTE
! end
end
puts 2.kilobytes
=> 2048
4
Monkeypatching
• Refers to the general idea of modifying the runtime code
without modifying the original source code
• Problems:
• Redefining existing methods
• Change methods used in other pieces of the code
• Ruby 2.0 introduced “scoped” monkeypatching
5
Objects and classes
• Objects contains instance variables
• Remember: instance variables exists only when assigned
• Objects contains:
• Instance variables
• Reference to its class
• object_id
class MyClass
! def my_method
! ! @v = 1
! end
end
obj = MyClass.new
obj.my_method
obj1
@v = 1
MyClass
my_method()
object
instance variables
class
methods
class
6
Classes are objects too
• class
• superclass
• All objects inherit from BasicObject
Class.superclass # => Module
Module.superclass # => Object
String.superclass # => Object
Object.superclass # => BasicObject
BasicObject.superclass # => nil
7
Classes and superclasses
obj1
obj2
MyClass
Object
Class
Module
class
class
class
superclass superclass
•What’s the class of Object ?
•What’s the superclass of Module ?
•What’s the class of Class ?
class MyClass; end
obj1 = MyClass.new
obj2 = MyClass.new
BasicObject
superclass
nil
superclass
8
Invoking methods
• Calling a method involves two steps:
1. Method lookup
• Identify receiver class
• Escalate ancestor chain until the method is found
2. Method execution
• The actual code is executed
class A; end
class B < A; end
B.ancestors
=> [B, A, Object, Kernel, BasicObject]
The ancestor chain
includes also modules
9
Ancestor chains
module M
! def my_method
! ! 'M#my_method'
! end
end
class C
! include M
end
class D < C; end
D
C
M
Object
Kernel
BasicObject
10
self
• Every line of Ruby is executed within an object
• Called current object: self
• Only one object holds the self at any given time
• Instance variables and methods (without explicit
receiver) are called on self
• In class or module definition the role of self is
taken by the class or module
class MyClass
! self! # => MyClass
end
11
Calling methods
dynamically
• Remember “sending messages to objects” ?
• Method send sends messages to objects
• Can be used to dynamically call methods
class MyClass
! def my_method(my_arg)
! ! my_arg * 2
! end
end
obj = MyClass.new
obj.send(:my_method, 3)! # => 6
12
Defining methods
dynamically
• Use the Module#define_method method
• Provide a block for the method body
class MyClass
! ["steve", "jeff", "larry"].each{|d|
! ! ! define_method d.to_sym do
! ! ! ! puts d
! ! ! end
! ! }
end
obj = MyClass.new
obj.steve! # => "steve"
obj.jeff! # => "jeff"
obj.larry! # => "larry"
13
method_missing
• What happens if no method is found in the ancestor
hierarchy?
• A method called method_missing is called
• A common idiom is to override this method in order
to intercept unknown messages
• Define ghost methods
• Methods that do not actually exists!
14
An example
class Mapper
! def initialize()
! ! @map = {}
! end
! def add(key, value)
! ! @map[key.downcase] = value
! end
! def method_missing(method_name, *args)
! ! key = method_name.to_s.downcase
! ! return @map[key] if @map.key? key
! end
end
m = Mapper.new
m.add("Rome","IT")
m.add("London","UK")
puts m.rome
puts m.london
15
instance_eval
• Allows to evaluate a piece of code within the
scope of an object
• That is: changes the self for a piece of code
class MyClass
! def initialize
! ! @v = 1
! end
end
obj = MyClass.new
obj.instance_eval do
! self!# => #<MyClass:0x83fd33 @v=1>
! @v! ! # => 1
end
v = 2
obj.instance_eval { @v = v}
obj.instance_eval { @v }! # => 2
BREAKS ENCAPSULATION!
Read/write private data
With great power comes
great responsibility!
16
class_eval
• Evaluates a block in the context of an existing class
• Changes the self (i.e., it reopens the class)
def add_method_to_(a_class)
! a_class.class_eval do
! ! def m
! ! ! "Hello!"
! ! end
! end!!
end
add_method_to String
"abc".m ! # => "Hello!"
More flexible than reopening
it with the class keyword
(i.e., parametric)
17
Singleton methods
• In Ruby it is possible to add a method to a single
instance of an object
str1 = "This is a string!"
str2 = "Another str"
def str1.title?
! self.upcase == self
end
str1.title?!# => false
str2.title?
=> NoMethodError: undefined method `title?' for "Another str":String
18
Singleton methods - 2
• Are stored in special classes called eigenclasses
• Invoking Object#class does not show eigenclasses
• Special syntax to enter in their scope
class << str1
! # Eigenclass scope
! def title?
! ! upcase == self
! end
end
#str1
title?
String
Object
str1
superclass
superclass
Eigenclass
Method lookup
revisited
19
Method aliases
• Introduce new names for methods
class MyClass
! def my_method; 'my_method()'; end
! alias :m :my_method
end
obj = MyClass.new
obj.my_method! # => "my_method()"
obj.m ! ! ! # => "my_method()"
class String
! alias :real_length :length
! def length
! ! real_length > 5 ? 'long' : 'short'
! end
end
We can invoke the method
with two names
Redefine but still use the old one
(this is also called around alias)
20
Kernel#eval
• Instead of taking a block, it takes a string containing the
code
• Code is executed and the result of expression is
returned
a = 1
b = 2
c = eval("a + b")
puts c
=> 3
Problems
• Code injection
• Readability
• etc.
21
Hook methods
• Various aspects of classes and method definition can
be caught at runtime
• Similar to events
• For example method_missing
class String
! def self.inherited(subclass)
! ! puts "#{self} was inherited by
#{subclass}"
! end
end
class MyString < String; end
=> "String was inherited by MyString"
module M
! def self.included(other_mod)
! ! "M was mixed into #{other_mod}"
! end
end
class C
! include M
end
=> "M was mixed into C"
22
References
23
Ad

More Related Content

What's hot (20)

A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
Paul Phillips
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
Wojciech Widenka
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Peter Maas
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
LearningTech
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
TypeScript
TypeScriptTypeScript
TypeScript
Oswald Campesato
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
Bobby Bryant
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
Solv AS
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
10 Things I Hate About Scala
10 Things I Hate About Scala10 Things I Hate About Scala
10 Things I Hate About Scala
Meir Maor
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
Sebastian Rettig
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
Pierre de Lacaze
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
Paul Phillips
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
Wojciech Widenka
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Peter Maas
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
Bobby Bryant
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
Solv AS
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
10 Things I Hate About Scala
10 Things I Hate About Scala10 Things I Hate About Scala
10 Things I Hate About Scala
Meir Maor
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 

Similar to Metaprogramming in Ruby (20)

Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
Christopher Haupt
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
Reuven Lerner
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
Pavel Tyk
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
Alex Koppel
 
Rapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsRapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on Rails
Simobo
 
Metaprogramming code-that-writes-code
Metaprogramming code-that-writes-codeMetaprogramming code-that-writes-code
Metaprogramming code-that-writes-code
orga shih
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013
rivierarb
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
Pharo
 
The Dark Side of Objective-C
The Dark Side of Objective-CThe Dark Side of Objective-C
The Dark Side of Objective-C
Martin Kiss
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
Marcus Denker
 
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
10 Techniques to writing easy yet stupidly thorough unit tests.pdf10 Techniques to writing easy yet stupidly thorough unit tests.pdf
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
Ortus Solutions, Corp
 
Metaprogramming With Ruby
Metaprogramming With RubyMetaprogramming With Ruby
Metaprogramming With Ruby
Farooq Ali
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
Aleksander Fabijan
 
6 Object Oriented Programming
6 Object Oriented Programming6 Object Oriented Programming
6 Object Oriented Programming
Deepak Hagadur Bheemaraju
 
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdfsingh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
Python advance
Python advancePython advance
Python advance
Mukul Kirti Verma
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
Anna (gaar4ica) Shcherbinina
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
AshokKumar587867
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
Christopher Haupt
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
Pavel Tyk
 
Rapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsRapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on Rails
Simobo
 
Metaprogramming code-that-writes-code
Metaprogramming code-that-writes-codeMetaprogramming code-that-writes-code
Metaprogramming code-that-writes-code
orga shih
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013
rivierarb
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
Pharo
 
The Dark Side of Objective-C
The Dark Side of Objective-CThe Dark Side of Objective-C
The Dark Side of Objective-C
Martin Kiss
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
Marcus Denker
 
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
10 Techniques to writing easy yet stupidly thorough unit tests.pdf10 Techniques to writing easy yet stupidly thorough unit tests.pdf
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
Ortus Solutions, Corp
 
Metaprogramming With Ruby
Metaprogramming With RubyMetaprogramming With Ruby
Metaprogramming With Ruby
Farooq Ali
 
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdfsingh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
Ad

Recently uploaded (20)

Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
AI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptxAI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptx
Shikha Srivastava
 
Cybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft CertificateCybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft Certificate
VICTOR MAESTRE RAMIREZ
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT StrategyRisk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
john823664
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
Middle East and Africa Cybersecurity Market Trends and Growth Analysis
Middle East and Africa Cybersecurity Market Trends and Growth Analysis Middle East and Africa Cybersecurity Market Trends and Growth Analysis
Middle East and Africa Cybersecurity Market Trends and Growth Analysis
Preeti Jha
 
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
User Vision
 
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
UXPA Boston
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
SOFTTECHHUB
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
AI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández VallejoAI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández Vallejo
UXPA Boston
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
AI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptxAI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptx
Shikha Srivastava
 
Cybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft CertificateCybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft Certificate
VICTOR MAESTRE RAMIREZ
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT StrategyRisk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
john823664
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
Middle East and Africa Cybersecurity Market Trends and Growth Analysis
Middle East and Africa Cybersecurity Market Trends and Growth Analysis Middle East and Africa Cybersecurity Market Trends and Growth Analysis
Middle East and Africa Cybersecurity Market Trends and Growth Analysis
Preeti Jha
 
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
User Vision
 
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
UXPA Boston
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
SOFTTECHHUB
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
AI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández VallejoAI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández Vallejo
UXPA Boston
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Ad

Metaprogramming in Ruby

  • 1. Metaprogramming in Ruby Nicola Calcavecchia - 24/04/2013 calcavecchia@{elet.polimi.it|gmail.com} Principles of Programming Languages 1
  • 2. Metaprogramming • Writing code that manipulates language constructs at runtime • In Ruby no distinction: • Same as “regular” programming • Enables: • Code that writes code • DSLs • Introspection (e.g., reflection) 2
  • 3. Introspection • Allows to get information about objects at runtime • Methods • Instance variables • etc. class MyClass ! def initialize() ! ! @var1, @var2 = 0, 2 ! end ! def my_method ! end end m = MyClass.new m.class => MyClass m.methods => # lot of methods ... m.instance_variables => [:@var1, :@var2] m.public_methods => # ... m.private_methods => # ... m.instance_of? MyClass => true m.instance_of? Object => false m.is_a? MyClass => true m.is_a? Object => true 3
  • 4. Open Classes • Classes can be “opened” for change • What about the open/closed principle? class MyClass ! def a; "method a"; end end m = MyClass.new m.methods - Object.new.methods => [:a] class MyClass ! def b; "method b"; end end m.methods - Object.new.methods => [:a, :b] class Numeric ! KILOBYTE = 1024 ! def kilobytes ! ! self * KILOBYTE ! end end puts 2.kilobytes => 2048 4
  • 5. Monkeypatching • Refers to the general idea of modifying the runtime code without modifying the original source code • Problems: • Redefining existing methods • Change methods used in other pieces of the code • Ruby 2.0 introduced “scoped” monkeypatching 5
  • 6. Objects and classes • Objects contains instance variables • Remember: instance variables exists only when assigned • Objects contains: • Instance variables • Reference to its class • object_id class MyClass ! def my_method ! ! @v = 1 ! end end obj = MyClass.new obj.my_method obj1 @v = 1 MyClass my_method() object instance variables class methods class 6
  • 7. Classes are objects too • class • superclass • All objects inherit from BasicObject Class.superclass # => Module Module.superclass # => Object String.superclass # => Object Object.superclass # => BasicObject BasicObject.superclass # => nil 7
  • 8. Classes and superclasses obj1 obj2 MyClass Object Class Module class class class superclass superclass •What’s the class of Object ? •What’s the superclass of Module ? •What’s the class of Class ? class MyClass; end obj1 = MyClass.new obj2 = MyClass.new BasicObject superclass nil superclass 8
  • 9. Invoking methods • Calling a method involves two steps: 1. Method lookup • Identify receiver class • Escalate ancestor chain until the method is found 2. Method execution • The actual code is executed class A; end class B < A; end B.ancestors => [B, A, Object, Kernel, BasicObject] The ancestor chain includes also modules 9
  • 10. Ancestor chains module M ! def my_method ! ! 'M#my_method' ! end end class C ! include M end class D < C; end D C M Object Kernel BasicObject 10
  • 11. self • Every line of Ruby is executed within an object • Called current object: self • Only one object holds the self at any given time • Instance variables and methods (without explicit receiver) are called on self • In class or module definition the role of self is taken by the class or module class MyClass ! self! # => MyClass end 11
  • 12. Calling methods dynamically • Remember “sending messages to objects” ? • Method send sends messages to objects • Can be used to dynamically call methods class MyClass ! def my_method(my_arg) ! ! my_arg * 2 ! end end obj = MyClass.new obj.send(:my_method, 3)! # => 6 12
  • 13. Defining methods dynamically • Use the Module#define_method method • Provide a block for the method body class MyClass ! ["steve", "jeff", "larry"].each{|d| ! ! ! define_method d.to_sym do ! ! ! ! puts d ! ! ! end ! ! } end obj = MyClass.new obj.steve! # => "steve" obj.jeff! # => "jeff" obj.larry! # => "larry" 13
  • 14. method_missing • What happens if no method is found in the ancestor hierarchy? • A method called method_missing is called • A common idiom is to override this method in order to intercept unknown messages • Define ghost methods • Methods that do not actually exists! 14
  • 15. An example class Mapper ! def initialize() ! ! @map = {} ! end ! def add(key, value) ! ! @map[key.downcase] = value ! end ! def method_missing(method_name, *args) ! ! key = method_name.to_s.downcase ! ! return @map[key] if @map.key? key ! end end m = Mapper.new m.add("Rome","IT") m.add("London","UK") puts m.rome puts m.london 15
  • 16. instance_eval • Allows to evaluate a piece of code within the scope of an object • That is: changes the self for a piece of code class MyClass ! def initialize ! ! @v = 1 ! end end obj = MyClass.new obj.instance_eval do ! self!# => #<MyClass:0x83fd33 @v=1> ! @v! ! # => 1 end v = 2 obj.instance_eval { @v = v} obj.instance_eval { @v }! # => 2 BREAKS ENCAPSULATION! Read/write private data With great power comes great responsibility! 16
  • 17. class_eval • Evaluates a block in the context of an existing class • Changes the self (i.e., it reopens the class) def add_method_to_(a_class) ! a_class.class_eval do ! ! def m ! ! ! "Hello!" ! ! end ! end!! end add_method_to String "abc".m ! # => "Hello!" More flexible than reopening it with the class keyword (i.e., parametric) 17
  • 18. Singleton methods • In Ruby it is possible to add a method to a single instance of an object str1 = "This is a string!" str2 = "Another str" def str1.title? ! self.upcase == self end str1.title?!# => false str2.title? => NoMethodError: undefined method `title?' for "Another str":String 18
  • 19. Singleton methods - 2 • Are stored in special classes called eigenclasses • Invoking Object#class does not show eigenclasses • Special syntax to enter in their scope class << str1 ! # Eigenclass scope ! def title? ! ! upcase == self ! end end #str1 title? String Object str1 superclass superclass Eigenclass Method lookup revisited 19
  • 20. Method aliases • Introduce new names for methods class MyClass ! def my_method; 'my_method()'; end ! alias :m :my_method end obj = MyClass.new obj.my_method! # => "my_method()" obj.m ! ! ! # => "my_method()" class String ! alias :real_length :length ! def length ! ! real_length > 5 ? 'long' : 'short' ! end end We can invoke the method with two names Redefine but still use the old one (this is also called around alias) 20
  • 21. Kernel#eval • Instead of taking a block, it takes a string containing the code • Code is executed and the result of expression is returned a = 1 b = 2 c = eval("a + b") puts c => 3 Problems • Code injection • Readability • etc. 21
  • 22. Hook methods • Various aspects of classes and method definition can be caught at runtime • Similar to events • For example method_missing class String ! def self.inherited(subclass) ! ! puts "#{self} was inherited by #{subclass}" ! end end class MyString < String; end => "String was inherited by MyString" module M ! def self.included(other_mod) ! ! "M was mixed into #{other_mod}" ! end end class C ! include M end => "M was mixed into C" 22
  翻译: