Block-ish expression?

I would like to conveniently create objects and define their methods right
at the point where I want to pass them into a method call. These objects are
a lot like blocks, except that I need more than one interface on them.

=== with a block
m(a, b) { |x| ... }
def m(a, b)
    yield
end

==== what I want
m(a, b, <inline_object_creation_expression_including: def foo, def bar>)

def m(a, b, c)
    if c.foo ...
    c.bar ...
end

Is there some convenient way to do this?

Thanks!

m(a, b, Class.new { def test; 13; end }.new)

···

On Thu, 18 Nov 2004 03:13:15 +0900, itsme213 <itsme213@hotmail.com> wrote:

I would like to conveniently create objects and define their methods right
at the point where I want to pass them into a method call. These objects are
a lot like blocks, except that I need more than one interface on them.

=== with a block
m(a, b) { |x| ... }
def m(a, b)
    yield
end

==== what I want
m(a, b, <inline_object_creation_expression_including: def foo, def bar>)

def m(a, b, c)
    if c.foo ...
    c.bar ...
end

Is there some convenient way to do this?

Thanks!

itsme213 wrote:

I would like to conveniently create objects and define their methods right
at the point where I want to pass them into a method call. These objects are
a lot like blocks, except that I need more than one interface on them.

It sounds a lot like prototype based OOP.

I guess something like this will do if you want a simpler syntax than the anonymous Class Bill Atkins suggested:

def object(base = Object.new, &block)
   result = base.clone
   result.instance_eval(&block)
   return result
end

m(a, b, object {
   def foo() ... end
   def bar() ... end
})

I usually do something like this:

class Object
def singleton_class # We'll ignore all the nomenclature issues
  class << self; self; end
end

def singleton_def(sym, &block)
  self.singleton_class.send(:define_method, sym, &block)
  self
end

def singleton_try(pass, sym, &block)
  self.singleton_def(sym, &block) if pass
  self
end
end

and then you can do stuff like:
m(a, b, Object.new.singleton_def(:foo) {|*args| p [:foo,
*args]}.singleton_try(rand(2) == 0, :meow) {|*args| ...}...)

I like Florian's solution, too.

~Me!

···

On Thu, 18 Nov 2004 03:38:16 +0900, Florian Gross <flgr@ccan.de> wrote:

itsme213 wrote:

> I would like to conveniently create objects and define their methods right
> at the point where I want to pass them into a method call. These objects are
> a lot like blocks, except that I need more than one interface on them.

It sounds a lot like prototype based OOP.

I guess something like this will do if you want a simpler syntax than
the anonymous Class Bill Atkins suggested:

def object(base = Object.new, &block)
   result = base.clone
   result.instance_eval(&block)
   return result
end

m(a, b, object {
   def foo() ... end
   def bar() ... end
})

--
There's no word in the English language for what you do to a dead
thing to make it stop chasing you.