23
Sep
09

borrowing groovy’s with statement



Here’s how you could implement Groovy’s with statement in Ruby :

class Object
   def with(&block)
      instance_eval(&block)
   end
end

# here's an example
f = File.open("file.txt","w")
f.with do
   puts "text"
   close
end

Advertisements

2 Responses to “borrowing groovy’s with statement”


  1. October 13, 2009 at 05:46

    This can be made even sexier with a small change:

    class Object
       def with(obj, &block)
          obj.instance_eval(&block)
       end
    end
    
    f = File.open("file.txt","w")
    with f do
       puts "text"
       close
    end
    

    It’s only slightly different, but I think when reading “with variable, do” makes more sense than, “variable dot with, do”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Blog Stats

  • 221,294 hits

%d bloggers like this: