Home > Uncategorized > Array to Hash in Ruby

Array to Hash in Ruby

a = [1, 2, 3]
Hash[*a.collect { |v| v, v*2].flatten]

or from something Ryan Carver was trying to do:


Array#to_h

I found myself writing something like this far too often:

def map_something(array)
  hash = {}
  array.each do |a|
    hash[a] = lookup_value a
  end
  hash
end

It bugged me every time, but digging through the Pick Axe never yielded (ahem) a simpler solution. What I wanted to do is this:

def map_something(array)
  array.to_h do |a|
    lookup_value a
  end
end

But of course you’d need Array#to_h. Here’s the cleverest implementation I could think of.

class Array
  def to_h(default=nil)
    Hash[ *inject([]) { |a, value| a.push value, default || yield(value) } ]
  end
end

A pointless example:

a = [1, 2, 3]
a.to_h do |v|
  [v * 2, v * 3]
end
> {1=>[2, 3], 2=>[4, 6], 3=>[6, 9]}

I love Array#inject!


			
Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.