AS core ext idea: Hash#transform_values

Mapping hash keys and values is tricky in Ruby. Mapping a hash returns an array, but we want a hash. Why bother coercing it every time?

To simplify that a bit, AS introduced Hash#transform_keys. I have noticed Rails source base still uses a few tricks to map values of hashes in different places. Additionally, applications built on top of Rails might experience the need to map hash values as well.

That said, I propose to extend Hash to allow this, in manner similar to #transform_keys:

{ a: 1, b: 2 }.transform_keys { |key| :"_#{key}" } # => { :_a => 1, :_b => 2 }

{ a: 1, b: 2 }.transform_values { |val| val ** 2 } # => { :a => 1, :b => 4 }

Yay or nay?

Changes to AS are very intrusive since they modify classes, getting something into AS is probably the hardest of all the libraries included in Rails. It doesn’t mean you shouldn’t try.

If you’re interested and passionate about making this change, I suggest making a new branch adding in the extra code to AS including tests as you normally would any change, then in a separate commit to the same branch clean up one or more of the places where you think using #transform_values could have a huge impact. This way anyone can easily see the value of having this method included in the AS codebase.

Yay or nay? I would need to see an implementation and usage to make that call.

I think I should have done this before even posting here… Well, I gave it more thought. As hash keys are usually symbols and strings, it makes perfect sense to map more or less unified things. Now, hash values are not usually unified so there are less applications of mapping over them.

I also walked and ack’d through Rails sources — turns out, places where hash values are mapped can be counted with fingers of one hand. And each of the occurrences does mapping a bit differently — one just needs a value to call #to_s on it, other needs also to know the key it was assigned to.

Looks like it’s safe to say it is just not worth it.


Gosha Arinich