A little Hash Goodness
Some quick refactoring this weekend had me throwing together some tidbits. {% highlight ruby %} module Enumerable # return Hash of enumeration to yielded values def collect_hash hash={} inject(hash) {|h,e| h[e] = block_given? ? yield(e) : nil; h } end # return Hash of enumeration to non-nil yielded values def select_hash hash={}, &block collect_hash(hash, &block).compact end end class Hash # return Hash with nil values removed def compact delete_if {|k,v| !v } end # array-style push of key-values def <<(hash={}) merge! hash end end {% endhighlight %} Yes, I know they've been done before, but they're quick one-liners and let me eliminate a lot of code. And as we all know, > the easiest code to maintain is the code you delete.