Forum: Ruby Should I use instance_eval or block.call

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0026dd77fd9ecc97b36e5b79cdbcf590?d=identicon&s=25 R. Kumar (sentinel)
on 2008-10-22 07:49
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?
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2008-10-22 09:10
(Received via mailing list)
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
This topic is locked and can not be replied to.