Instance_eval

I would like to write a function which evaluates
a block in the ontext of an object.
I tried something like that (of course it did not work):

class MyClass
attr_reader :test
end

def f(&block)
x = MyClass.new
x.instance_eval(&block)
x
end

puts( (f { @test = 1 } ).test )

I would like to achieve that the code block of f
is evaluated in the context of the new MyClass object.
It is evaluated in the main context.

Is there a way to rewrite my f function so that
the last line of the code prints 1 instead of nil,
or is it pricipially impossible in Ruby?

Regards, Christian

Christian Szegedy wrote:

I would like to achieve that the code block of f
is evaluated in the context of the new MyClass object.
It is evaluated in the main context.

Is there a way to rewrite my f function so that
the last line of the code prints 1 instead of nil,
or is it pricipially impossible in Ruby?

What version are you using? I get “1” on both
ruby 1.6.6 (2001-12-26) [i586-linux-gnu] and
ruby 1.7.2 (2002-07-13) [i686-linux]

···


([ Kent Dahl ]/)_ ~ [ http://www.stud.ntnu.no/~kentda/ ]/~
))_student
/(( _d L b_/ NTNU - graduate engineering - 5. year )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)

Kent Dahl wrote:

Christian Szegedy wrote:

I would like to achieve that the code block of f
is evaluated in the context of the new MyClass object.
It is evaluated in the main context.

Is there a way to rewrite my f function so that
the last line of the code prints 1 instead of nil,
or is it pricipially impossible in Ruby?

What version are you using? I get “1” on both
ruby 1.6.6 (2001-12-26) [i586-linux-gnu] and
ruby 1.7.2 (2002-07-13) [i686-linux]

You are right.

(Sorry, I had a typo and therefore my program did not work, but
I sent the a simplified but correct version to the newsgroup.)

Thanks a lot!