Cleaning up a Ruby hash

Aug 31, 2015
ruby, tech
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:

1
2
3
4
5
hash = {one: "  one  ", two: "two  "}
hash.each do |key, value|
  hash[key] = value.strip!
end
#=> {:one=>“one”, :two=>“two”}

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

1
2
["  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)

1
2
3
4
5
6
7
class Hash
  def clean(&block)
    each { |key, value|
      self[key] = yield(value)
    }
  end
end

Now it’s as easy as,

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

Now I can easily sanitise Rails parameter hashes

1
2
3
def model_params
  params.require(:model).permit(:name, :email, :phone).clean(&:strip!)
end
comments powered by Disqus