On Mon, Jul 10, 2006 at 07:33:34PM +0900, Erik Veenstra wrote:
> Okay, criticizing somebody's work without providing a
> "solution", isn't nice at all...

nah, what matters is *improving* the code (and focusing on it)

> PS: I'm still curious about the reason for using a module.

As I said, it reduces pollution and makes it work with frozen and immediate
values. See the unit tests and the explanation at
http://eigenclass.org/hiki.rb?instance_exec.

>  class Object
>    def instance_exec(*args, &block)
>      object      = self
>      res         = nil
> 
>      class << self
>        self
>      end.instance_eval do
>        begin
>          Thread.critical = true
>          @_instance_exec_count_ ||= 0
           ======================
adds an instance variable for each object to which we send the instance_exec
message (fails for frozen objects, pollutes and costs more memory)
>          @_instance_exec_count_ += 1
>          method_name = "_instance_exec_#{@_instance_exec_count_}_"
>        ensure
>          Thread.critical = false
           =======================
The old Thread.critical value is lost, so this could easily break
multi-threaded code... It should be
  begin  
      old, Thread.critical = Thread.critical, true
      ...
  ensure
      Thread.critical = old
  end
  
>        end
> 
>        begin
>          define_method(method_name, &block)
> 
>          res = object.send(method_name, *args)
>        ensure
>          remove_method(method_name) rescue nil
>        end
>      end

All in all, this implementation is the second best one as far as space
efficiency is concerned ;)

I don't like having to point to my own site repeatedly, but you should really
have a look at

  http://eigenclass.org/hiki.rb?bounded+space+instance_exec
 
So far all the implementations I've seen posted were worse than the one shown
there (and than the original one in my older blog entry). It's the only
thread-safe, reentrant, bounded-space, frozen-object-safe implementation as
far as I know.

-- 
Mauricio Fernandez  -   http://eigenclass.org   -  singular Ruby