Cleaning up a Ruby hash

Hash#clean, a monkey patch to provide easy, Array#map like access to hash values to update them inline.

I’ve found a number of times where I have needed to iterate over a hash and modify the values. The most recent was stripping excess spaces from the values of a Rails params hash.

The only way I know of doing this is:

hash = {one: "  one  ", two: "two  "}
hash.each do |key, value|
  hash[key] = value.strip!
#=> {:one=>“one”, :two=>“two”}

This is a lot less elegant than using map on an Array

["  one  ", "two  "].map(&:strip!)
#=> ["one", "two"]

I wanted something like #map for a Hash

So I came up with Hash#clean (this is a monkey patch so exercise with caution)

class Hash
  def clean(&block)
    each { |key, value|
      self[key] = yield(value)

Now it’s as easy as,

{one: "  one  ", two: "two  "}.clean(&:strip!)
#=> {:one=>"one", :two=>"two"}

Now I can easily sanitise Rails parameter hashes

def model_params
  params.require(:model).permit(:name, :email, :phone).clean(&:strip!)
Aug 31, 2015 tech, ruby
comments powered by Disqus