From: Gary Wright Date: 2007-04-11T07:50:57+09:00 Subject: Re: Procs vs. nested methods and variable scope... On Apr 10, 2007, at 3:45 PM, Jay McGavren wrote: > I'm going to be re-using this technique at quite a few places in my > code, so I want to be certain I have it right... > > I started with code like this, within a method: > > for playlist in playlists > with_option_values('find', config) do |terms| > if (results = playlist.Search(terms, 0)) > results.each {|track| tracks.push(track)} > end > end > with_option_values('visible-find', config) do |terms| > if (results = playlist.Search(terms, 1)) > results.each {|track| tracks.push(track)} > end > end > #Repeat several more times... > end What is that second argument to Search? Is it just an index of some sort such that 'find' is the first search (index 0) and 'visible-find' is the second search (index 1) and so on? Also, it is a bit strange to have a method capitalized. If you change the definition of Search to return an empty array instead of nil or false when it finds no matches and that second argument to Search is just an index as I described then I think you can wrap everything up as: results = [] playlists.each do |playlist| %w{find visible-find}.each_with_index do |option, index| with_option_values(option, config) do |terms| results += playlist.Search(terms, index) end end end No need to create methods or procs. I tossed the (for...in) constructs since 'each' is more Ruby-like but you could easily use for..in if that reads better to you. And if you like using inject: results = playlists.inject([]) do |list, playlist| %w{find visible-find}.each_with_index do |option, index| with_option_values(option, config) do |terms| list += playlist.Search(terms, index) end end end If the second argument to Search is not strictly increasing with the option names you could iterate over an array of values: [['find', 0], ['visible-find', 1], ['other-opt', 5]].each do | option, search| #... end If you need Search to return nil you could do something like: results += playlist.Search(terms, index) || [] Gary Wright