Created
May 6, 2011 02:07
-
-
Save daqing/958331 to your computer and use it in GitHub Desktop.
Ruby Meta Programming Explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Class | |
def where | |
"in class Class" | |
end | |
end | |
person = Class.new | |
puts "person.where: #{person.where}" # => "in class Class" | |
class << person | |
def where | |
"in class person's metaclass" | |
end | |
end | |
puts "person.where: #{person.where}" # => "in class person's metaclass" | |
def person.where | |
"in class person's metaclass, redefined" | |
end | |
puts "person.where: #{person.where}" # => "in class person's metaclass, redefined" | |
meta_person = class << person; self; end | |
meta_person.class_eval do | |
def where | |
"in class person's metaclass, redefined again" | |
end | |
end | |
puts "person.where: #{person.where}" # => "in class person's metaclass, redefined again" | |
person.class_eval do | |
def where | |
"in class person" | |
end | |
end | |
daqing = person.new | |
puts "daqing.where: #{daqing.where}" # => "in class person" | |
def daqing.where | |
"in daqing's metaclass" | |
end | |
puts "daqing.where: #{daqing.where}" # => "in daqing's metaclass" | |
meta_daqing = class << daqing; self; end | |
meta_daqing.class_eval do | |
def where | |
"in daqing's metaclass, redefined" | |
end | |
end | |
puts "daqing.where: #{daqing.where}" # => in daqing's metaclass, redefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment