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?

1

2 Answers 2

7

Hash[] constructs a hash from array.

Hash[array.map {|el| el.split ':'}]
Sign up to request clarification or add additional context in comments.

Comments

7

I believe ruby 2.1 has a .to_h method.

Therefor,

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

will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.