Skip to content

Instantly share code, notes, and snippets.

@esumerfd
Created September 20, 2010 21:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esumerfd/588682 to your computer and use it in GitHub Desktop.
Save esumerfd/588682 to your computer and use it in GitHub Desktop.
#
# 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