Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Created January 12, 2011 23:39
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 hopsoft/777118 to your computer and use it in GitHub Desktop.
Save hopsoft/777118 to your computer and use it in GitHub Desktop.
Dynamic Method - Illustrates how to define methods dynamically at runtime
# 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