Array#to_h redux
Since the last post I've been really busy writing code, moving into a new house and being sick. So first off, apologies for the lack of content here.
Next. Confession. I made a fatal flaw when coming up with Array#to_h. I didn't need it. Well, I needed something but it wasn't exactly what that method turned out to be. I got caught up trying to make a cool one liner (but learned a lot about Hash while doing it).
Turns out sometimes I wanted to play with keys, sometimes values and sometimes both. Turns out all I needed was something simple like this:
class Array # yield each value of the array and a hash, return the hash def to_h(hash={}) each { |value| yield hash, value } hash end end
Because really the only thing that bugged me about doing it inline was having to return the hash.. that dangling return value just never feels right. This tightens it up just enough.
def map_something(array) array.to_h do |hash, value| hash[value.to_sym] = transform_value value end end
By the way, making hash a parameter to the method lets you do cool things like assign default values to all new elements. Another pointless example:
h = Hash.new { |hash,key| hash[key] = 5 } [1,2,3].to_h(h) do |hash,value| hash[value] *= value end => {1=>5, 2=>10, 3=>15}
So, one dangling issue. Should this be a method of Array or Enumerable? If Enumerable it should probably be overridden for Hash as Hash#to_h should simply return self.