From: Andy Lowry Date: 2013-07-23T05:38:12+09:00 Subject: Re: tap { break } idiom deserves its own Kernel method? This is my first code sample but with one temporary variable removed. Getting rid of the remaining temp variable is much more difficult. You could inline the "Model.where..." expression but then you'd end up executing it repeatedly in the id_list loop. The reason I use the idiom is to avoid cluttering my namespace with names for things that are of ephemeral interest, i.e. only useful as a step in achieving some needed value. In my opinion, those values are less prominent in the "pipe" version of my code than in either my first code sample or in your code, and that seems valuable to me. The only thing that seems arcane to me in this thread is using break inside tap; as I pointed out, it's something a lot of ruby coders won't understand. Code blocks with well-defined behaviors are obviously well understood by any ruby developer who's not a total novice. I believe that "pipe" would take a useful idiom that is seen occasionally (not just in my code) and is arcane because of the tap/break combo, and provide a non-arcane alternative. Andy Robert Klemme wrote in post #1116270: > On Mon, Jul 22, 2013 at 7:37 PM, Andy Lowry > wrote: > >> the order their ids appear in that list. >> >> it a name and its own Kernel method, rather than forcing the use of a >> Then the example above turns into: >> >> sorted = Model.where(id: id_list).pipe do |unsorted| >> unsorted.reduce(Hash.new) {|h,o| h[o.id] = o; h} >> end.pipe do |objs_map| >> id_list.map{|id| objs_hash[id]} >> end >> >> Any thoughts? >> > > I would choose a much less arcane solution: > > objs_map = {} > Model.where(id: id_list).each {|o| objs_map[o.id] = o} > sorted = id_list.map{|id| objs_map[id]} > > If id_list is smallish (< 30 or so) then index lookup might actually be > faster - or at least fast enough. > > sorted = Model.where(id: id_list).sort_by {|o| id_list.index(o)} > > Kind regards > > robert -- Posted via http://www.ruby-forum.com/.