[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Should I use instance_eval or block.call

Nit Khair

10/22/2008 5:48:00 AM

I am writing a library that will be used by others. Have been reading a
lot about procs/blocks etc, and the difference between block.call and
instance_eval pointed out in some articles was the context they are
executed in.

So if I put instance_eval in my method, the user of my lib can call
methods in a block without using an instance. Otherwise, he has to use
the instance to call a method.
That means that the user has to know whether I have used block.call in
my source or instance_eval.

Other than that, how do i decide which to use ? Are there any other pros
and cons?
--
Posted via http://www.ruby-....

1 Answer

Robert Klemme

10/22/2008 7:08:00 AM

0

2008/10/22 Nit Khair <sentinel.2001@gmx.com>:
> I am writing a library that will be used by others. Have been reading a
> lot about procs/blocks etc, and the difference between block.call and
> instance_eval pointed out in some articles was the context they are
> executed in.
>
> So if I put instance_eval in my method, the user of my lib can call
> methods in a block without using an instance.

This is also true for block.call - it's just another instance. :-)

> Otherwise, he has to use
> the instance to call a method.
> That means that the user has to know whether I have used block.call in
> my source or instance_eval.
>
> Other than that, how do i decide which to use ? Are there any other pros
> and cons?

It seems there is a tendency to use block call and yield self because
it is more obvious. Also, in case of attribute setters using
instance_eval does not really help because of the local variable
method ambiguity:

irb(main):001:0> Foo = Struct.new :bar do def test(&b) instance_eval(&b) end end
=> Foo
irb(main):002:0> f=Foo.new
=> #<struct Foo bar=nil>
irb(main):003:0> f.test { bar = 10 }
=> 10
irb(main):004:0> f
=> #<struct Foo bar=nil>
irb(main):005:0> f.test { self.bar = 10 }
=> 10
irb(main):006:0> f
=> #<struct Foo bar=10>
irb(main):007:0>

Having said that, the situation for DSL's is different: here it is
often desired to not have to use an instance for cleaner syntax and
you want to provide some context. In those cases it's probably better
to use instance_eval.

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end