Should I use instance_eval or block.call


#1

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?


#2

2008/10/22 Nit K. removed_email_address@domain.invalid:

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. :slight_smile:

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
=> #
irb(main):003:0> f.test { bar = 10 }
=> 10
irb(main):004:0> f
=> #
irb(main):005:0> f.test { self.bar = 10 }
=> 10
irb(main):006:0> f
=> #
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