Hi,
The main problem here, I think, is the context of the blocks you are passing. They are bound into the current context. When you say 'foop = proc { yield * 2 }', the yield is for the current context, where there is no block to yield to.
Here's an example of the strange way contexts work when you define methods using blocks/procs:
# set some variables
foo, bar, baz = 23, 42, 93
==>[23, 42, 93]
# create a class, define a method which shows the values of foobarbaz
c = Class.new
==>#<Class:0x713c4>
c.send :define_method, :inspect, lambda{"foo=#{foo}; bar=#{bar}; baz=#{baz}"}
==>#<Proc:0x0006149c@(irb):8>
#inspect it:
c.new
==>foo=23; bar=42; baz=93
#change a value
baz = 144
==>144
c.new
==>foo=23; bar=42; baz=144
In Ruby 2.0, you will be able to do something like this:
c = Class.new
foop = lambda {|&b| b.call * 5 }
c.send(:define_method, :foo, foop)
But, currently, I think there is no way to do that. I suppose you could do this:
c=Class.new
==>#<Class:0x8c5ac>
def foop() yield*2 end
==>nil
c.send(:define_method, :foo, method(:foop))
==>#<Method: Object#foop>
c.new.foo{5}
==>10
... But I get the feeling you are looking for a way to define methods using only methods.
cheers,
Mark
···
On Jun 9, 2004, at 3:53 AM, Csaba Henk wrote:
Hi!
The following, of course, works fine:
class C
def foo
yield * 2
end
end
C.new.foo {5}
=> 10
but if I do:
foop = proc { yield * 2 }
then
foop.call {5}
doesn't pass the block to yield, and if I define c as:
c = Class.new
c.send(:define_method,:foo,foop)
then
c.new.foo {5}
neither works.
Is there a way to define a method like the foo of C in the
c.send(:define_method,...) way?