Should I use instance_eval or block.call

N

Nit Khair

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?
 
R

Robert Klemme

2008/10/22 Nit Khair said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top