A very small Ruby method


I haven’t had much time or inclination for blogging lately. Not much happening at the moment, actually. But I came up with one small thing I wanted to document. Just a practical thing for certain situations. Basically it’s a with-method, that works fairly well. It’s nothing magical and the trick is basic. It’s more or less an alias, actually:

module Kernel
def with(obj = nil, &block)
(obj || self).instance_eval &block
end
end

with("abc") do
puts reverse
end

"abc".with do
puts reverse
end

As you can see, insstance_eval can be used like JavaScript or VB’s with. This is nice for the simple reason of documentation. I find this usage much easier to read and understand than most usages of instance_eval that I’ve seen.

So, that’s it for today. I’ll probably be back soon with some recent JRuby developments too.


4 Comments, Comment or Ping

  1. Daniel Spiewak

    Neat trick! It’s not really fancy Ruby or anything, but it’s a cool application of the syntax that’s been there all this time. Props.

    December 14th, 2006

  2. Josh

    This is somewhat like the #returning method in Rails’ ActiveSupport library:

    def returning(value)
    yield(value)
    value
    end

    You use it like:
    returning obj { |obj| obj.mutate! }

    It’s essentially the K combinator for Ruby. I like the #returning approach better as it avoids using #instance_eval.

    January 2nd, 2007

  3. Nigel

    I love this. Very cool.

    My only concern is this allows blocks to access member variables directly [due to the use of instance_eval]

    so if class A has a member @a…

    with (A.new) do
    @a = ‘something else’
    end

    executes fine. This worries me.

    March 8th, 2007

  4. Bug

    Of course it does. As he said, it’s an alias to instance_eval, in effect. That’s why I’d prefer not to make the alias, since ‘with’ implies a slightly different funcitonality.

    March 23rd, 2007

Reply to “A very small Ruby method”