Created
January 7, 2011 02:47
-
-
Save sgharms/769029 to your computer and use it in GitHub Desktop.
an idea about module generation
This file contains hidden or 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
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm looking for any ideas on how to pretty up the line 10 step. That feels ugly to me.