Hi -talk,
Ruby has wonderful support for chewing and spitting arrays. For
instance, it’s easy to produce an array from any Enumerable using
#map. With hashes, however, it’s a bit more cumbersome.
For example, the following method is typical of my code:
# return { filename -> size }
def get_local_gz_files
files = {}
Dir["*.gz"].each do |filename|
files[filename] = File.stat(filename).size
end
files
end
The pattern is: create an empty hash, populate it, and return it. Now
Ruby is a wonderfully expressive and terse language. Accordingly, the
two lines devoted to initialising and returning the hash in the above
code seem wasted.
If Ruby had Array#to_h, then I could rewrite it as:
# return { filename -> size }
def get_local_gz_files
Dir["*.gz"].map { |filename|
[ filename, File.stat(filename).size ]
}.to_h
end
The proposed implementation of Array#to_h is per the following code:
class Array
def to_h
hash = {}
self.each do |elt|
raise TypeError unless elt.is_a? Array
key, value = elt[0…1]
hash[key] = value
end
hash
end
end
For the final justification, note that this is the logical reverse of
Hash#to_a:
h = {:x => 5, :y => 10, :z => -1 }
a = h.to_a # => [[:z, -1], [:x, 5], [:y, 10]]
And now, for my next trick…
a.to_h == h # => true (gosh, that actually worked)
Thoughts?
Gavin