Created
January 12, 2011 23:39
-
-
Save hopsoft/777118 to your computer and use it in GitHub Desktop.
Dynamic Method - Illustrates how to define methods dynamically at runtime
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
# setup some data that will drive what methods get defined | |
$method_names = [:hello, :goodbye] | |
# define our example class | |
class Example | |
# define some dynamic methods | |
$method_names.each do |method_name| | |
define_method(method_name) do |name| | |
puts "#{method_name} #{name}!" | |
end | |
end | |
end | |
# test out our dynamic methods | |
Example.new.respond_to? :hello # => true | |
Example.new.respond_to? :goodbye # => true | |
Example.new.hello("nathan") # => hello nathan! | |
Example.new.goodbye("nathan") # => hello nathan! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment