Skip to content

Instantly share code, notes, and snippets.

@daqing
Created May 6, 2011 02:07
Show Gist options
  • Save daqing/958331 to your computer and use it in GitHub Desktop.
Save daqing/958331 to your computer and use it in GitHub Desktop.
Ruby Meta Programming Explained
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