ruby tip

March 15, 2007 | In: rails, ruby

Here is a quick ruby function that takes a array of objects
(could be the resultset from a find call) and a member name
and creates a multimap collection (basically a hash of arrays)
that can then be easily displayed in a threaded manor.

def segment_by_field(objs,member='unthreaded')
  retVals = Hash.new
  prev_val = nil
  for obj in objs
    if member != 'unthreaded'
      current_val = obj.send(member)
      if prev_val.nil? or !retVals.has_key?(current_val)
        retVals[current_val] = Array.new
      end
      prev_val = current_val
      retVals[prev_val] << obj
    else
      retVals[member] = Array.new unless retVals.has_key?(member)
      retVals[member] << obj
    end
  end
  return retVals
end
Bookmark and Share
blog comments powered by Disqus

Flickr Pics

13th and washington NYC13th and 9th NYC1st st Jersey CityIMG_2813IMG_2814_2IMG_2816IMG_2815Photo_011908_001Photo_122807_001Photo_121107_001