On Fri, Jul 6, 2012 at 12:17 PM, Rodrigo Rosenfeld Rosas
<rr.ro...@gmail.com> wrote:
> myLongListNameIDontWantToRepeat.tap do |l|
>   l.psize
>   l.add 10
>   l.psize
>   ...
> end

I was going to suggest #tap myself, but I realized it's not as "bare"
as instance_eval/exec. It is certainly unfortunate that
instance_eval/exec cause a singleton object to come into existence
immediately. Unfortunately if they do not any method definitions fail
in a horrible way: they define themselves on the actual class.

It is possible to define a "new" instance_eval that uses a dummy
class, so that definitions fail immediately, for DSL purposes...

irb(main):001:0> s = 'foo'
=> "foo"
irb(main):002:0> s.instance_exec_light { puts to_s }
foo
=> nil
irb(main):003:0> s.instance_exec_light { def foo; end }
TypeError: no class/module to add method
        from (irb):3:in `evaluate'
        from org/jruby/RubyBasicObject.java:1846:in `instance_exec_light'
        from (irb):3:in `evaluate'
        from org/jruby/RubyKernel.java:1045:in `eval'
        from org/jruby/RubyKernel.java:1361:in `loop'
        from org/jruby/RubyKernel.java:1154:in `catch'
        from org/jruby/RubyKernel.java:1154:in `catch'
        from /Users/headius/projects/jruby/bin/jirb:13:in `(root)'

This "instance_exec_light" does not create a singleton object, and as
a result it is massively faster (and doesn't have the same Java
integration problems) :

system ~/projects/jruby $ jruby -rbenchmark -e "5.times { puts
Benchmark.measure { 1000000.times { s = 'foo'; s.instance_exec { to_s
} } } }"
  5.330000   0.340000   5.670000 (  2.279000)
  3.630000   0.330000   3.960000 (  1.693000)
  3.490000   0.350000   3.840000 (  1.671000)
  3.510000   0.330000   3.840000 (  1.654000)
  3.470000   0.330000   3.800000 (  1.644000)

system ~/projects/jruby $ jruby -rbenchmark -e "5.times { puts
Benchmark.measure { 1000000.times { s = 'foo'; s.instance_exec_light {
to_s } } } }"
  1.290000   0.050000   1.340000 (  0.675000)
  0.310000   0.020000   0.330000 (  0.288000)
  0.280000   0.020000   0.300000 (  0.281000)
  0.290000   0.030000   0.320000 (  0.284000)
  0.290000   0.020000   0.310000 (  0.281000)

I don't know if such an idea would be accepted by Matz or ruby-core,
but it seems like a useful feature to me.

- Charlie

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


Reply via email to