Skip to content

Useful core extensions

golive edited this page Sep 28, 2011 · 1 revision

Smarter Hash inverse

Example: {1=>'a', 2=>'b', 3=>'a', 4=>'b'}.reverse # => {"a"=>[1, 3], "b"=>[2, 4]}

class Hash
  def reverse
    h = Hash.new
    self.each_pair { |v,k| h[k] = h[k] ? Array(h[k]) << v : v }
    return h
  end
end
Clone this wiki locally