Created
October 22, 2014 10:11
-
-
Save buren/f095ba721e2926d8e597 to your computer and use it in GitHub Desktop.
Simple Ruby meta programming example
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 Meta | |
def self.make_method(meth_name) | |
define_method meth_name do |adjective| | |
puts "#{meth_name} is a #{adjective} method name" | |
end | |
end | |
def method_missing(meth, *args, &block) | |
puts "Method #{meth} is not defined on this class" | |
self.class.make_method(meth) | |
end | |
end | |
m = Meta.new | |
Meta.make_method('my_method') # => Define method named 'my_method' | |
m.my_method('fine') # => 'my_method is a fine method name a' | |
m.my_method('nice') # => 'my_method is a nice method name a' | |
m.mm('missing') # => Hits method missing | |
m.mm('previously missing') # => 'mm is a previously missing method name' | |
Meta.make_method('abc') # => Define method named 'abc' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment