From: Allen Lee Date: 2010-01-22T21:25:05+09:00 Subject: Re: Ruby equivalent of C# "using keword" and IDispose --00504502b875797acc047dbfe022 Content-Type: text/plain; charset=ISO-8859-1 1) I also considered def using(res, close = :close) over def using(res, options = { release_with: :close }) however, I think using(Res.new, release_with: "close") would be nicer than using(Res.new, "close") so finally I chose what it is right now :) 2) The solution you provided as follows is definitely more robust due to respond_to? may not work as expected in the situation you mentioned and thanks! res.send(options[:release_with]) rescue nil allen On Fri, Jan 22, 2010 at 5:32 PM, Robert Klemme wrote: > 2010/1/22 Allen Lee : > > I finally came up with this toy: > > This looks interesting. Although I have to say that the functionality > should be rather built into the classes at hand (like e.g. File has) > IMHO. > > > def using(res, options = { release_with: :close }) > > Since you have a single option only you can as well do > > def using(res, close = :close) > > > yield res > > ensure > > if res.respond_to?(options[:release_with]) > > res.send(options[:release_with]) > > end > > I'd rather do > > res.send(options[:release_with]) rescue nil > > Because the idea of respond_to? and what the class really understands > may differ. > > irb(main):001:0> class X > irb(main):002:1> def method_missing(s,*a,&b) > irb(main):003:2> "I can #{s}!" > irb(main):004:2> end > irb(main):005:1> end > => nil > irb(main):006:0> o = X.new > => # > irb(main):007:0> o.respond_to? :dance > => false > irb(main):008:0> o.dance > => "I can dance!" > irb(main):009:0> o.dance! > => "I can dance!!" > irb(main):010:0> > > > end > > > > Note that you need to go back to :release_with => "close" if you are > > targeting version before 1.9. > > This is not necessary if you just use a single additional parameter (see > above). > > Kind regards > > robert > > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ > > --00504502b875797acc047dbfe022--