0

I have this:

[["hello", 1], ["world", 1]] 

I want this:

{ "hello" => 1, "world" => 1 }

I've coded something that WORKS, but feels stupid. Here it is:

hash = {}
array.each do |element|
  hash[element[0]] = element[1]
end 
hash

Is there a better way?

1 Answer 1

1

Yes.. do as below using Hash[ [ [key, value], ... ] ] → new_hash

Hash[[["hello", 1], ["world", 1]]] # =>  => {"hello"=>1, "world"=>1} 

If you are in Ruby2.1 use Array#to_h

[["hello", 1], ["world", 1]].to_h
Sign up to request clarification or add additional context in comments.

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.