Skip to content

Instantly share code, notes, and snippets.

@sgharms
Created January 7, 2011 02:47
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 sgharms/769029 to your computer and use it in GitHub Desktop.
Save sgharms/769029 to your computer and use it in GitHub Desktop.
an idea about module generation
#!/usr/bin/env ruby
class FirstClass
def initialize
@someArray = %w(foo bar bat)
end
def create_module
a_var = @someArray
Module.new do
# This defines instance methods on the Module
# m.instance_methods #=> [:say_foo, :say_bar, :say_bat]
# Note, you can't use @someArray in the iteration because
# self has changed to this anonymous module. Since a block
# is a binding, it has the local context (including a_var)
# bundled up with it -- despte self having changed!
# Therefore, this works
a_var.each do |m|
define_method "say_#{m}".to_sym do
puts "Here I am in say_#{m}"
end
end
end
end
end
class Larry
include FirstClass.new.create_module
end
l = Larry.new
l.say_bar
@sgharms
Copy link
Author

sgharms commented Jan 7, 2011

I'm looking for any ideas on how to pretty up the line 10 step. That feels ugly to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment