Created
September 20, 2010 21:30
-
-
Save esumerfd/588682 to your computer and use it in GitHub Desktop.
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
# | |
# After a discussion about the cool groovy syntax for | |
# declaring anonymous classes. Jim Weirich and I came up | |
# with the following solutions in Ruby. | |
# | |
# Requires: Ruby 1.9 | |
# | |
def run(x) | |
x.foo | |
end | |
class Object | |
def anon(name, &block) | |
Class.new do | |
define_method name, block | |
end.new | |
end | |
end | |
run( anon(:foo) { puts "IN FOO from Object method" } ) | |
class Symbol | |
def def(&block) | |
the_symbol = self | |
Class.new do | |
define_method the_symbol, block | |
end.new | |
end | |
end | |
run( :foo.def { puts "IN FOO from Symbol" } ) | |
class Proc | |
def named(name) | |
the_proc = self | |
Class.new do | |
define_method name, the_proc | |
end.new | |
end | |
end | |
run -> { puts "IN FOO from Proc" }.named(:foo) | |
class Hash | |
def anon | |
the_hash = self | |
Class.new do | |
the_hash.each do |name, function| | |
define_method(name) { function.call } | |
end | |
end.new | |
end | |
end | |
run( { foo: -> { puts "IN FOO from Hash" } }.anon ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment