Skip to content

Instantly share code, notes, and snippets.

@slant
Created January 6, 2014 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slant/8288657 to your computer and use it in GitHub Desktop.
Save slant/8288657 to your computer and use it in GitHub Desktop.
Experimenting with metaprogramming in Ruby.
class Thing
def self.format_answer_for(question_title, &block)
define_method("__format_answer_for_#{question_title}", &block)
end
end
#################
## Test Case 1 ##
#################
# Define a new instance method using an arbitrary string ("testing")
Thing.format_answer_for("testing") { puts "O HAI" }
# Call the method directly
Thing.new.__format_answer_for_testing # O HAI
#################
#################
## Test Case 2 ##
#################
# Define another new instance method, store it
thing = Thing.format_answer_for("another") { puts "WAT" }
# Output instance methods for class Thing
puts Thing.instance_methods - Object.methods # __format_answer_for_another
# Call the new instance method
thing.call # WAT
#################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment