3

I have an array

["bob:12 elm st", "sally:100 digital ave", "tom:2324 elmhurst st"] 

which I need to convert to

{"bob" => "12 elm st", "sally" => "100 digital ave", "tom" => "2324 elmhurst st"}.

I know I can do

array.each do |e|
  k = e.split(":").first
  v = e.split(":").last
  hash[k] = v
end

Is there a more elegant way to do this?

Jason Michael
  • 516
  • 5
  • 16
  • possible duplicate of [What is the best way to convert an array to a hash in Ruby](http://stackoverflow.com/questions/39567/what-is-the-best-way-to-convert-an-array-to-a-hash-in-ruby) – Yossi May 13 '14 at 16:32

2 Answers2

7

Hash[] constructs a hash from array.

Hash[array.map {|el| el.split ':'}]
Yossi
  • 11,778
  • 2
  • 53
  • 66
7

I believe ruby 2.1 has a .to_h method.

Therefor,

array.map { |i| i.split ':' }.to_h 

will work.

Cereal
  • 3,699
  • 2
  • 23
  • 36