Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

using object(s) do ... (See related posts)

A little meta-hack that allows one to temporarily assign one or more objects into the scope of a block. My thanks to vinterbleg for optimizing it.

def using (*args)
  yield *args
end


For (a rather half-assed) example:

>> using [10,20,30], 40 do |x,y|
>>   x << y if y.is_a? Fixnum
>>   puts x.to_s
>> end
10203040
=> nil

Comments on this post

vinterbleg posts on Apr 13, 2008 at 08:45
Can be rewritten as:

def using(*args)
    yield *args
end


The error checking is done automatically, and the &block argument is unnecessary when using yield.
bleeder posts on Apr 14, 2008 at 10:01
True, error checking is done automatically, but the errors produced are not always very descriptive to the actual problem - that's why I decided to add my own error check.

You need to create an account or log in to post comments to this site.


Click here to browse all 4836 code snippets

Related Posts