Dan Sharp
Dan Sharp

Reputation: 1279

Turn an array into a hash with keys matching values

If I have the following array:

foo = ['a', 'b', 'c', 'd', 'e']

Is there a simple way in Ruby to make it into a hash that looks like:

{ 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', 'e' => 'e' }

I can do this:

Hash[foo.map{|a| [a, a]}]

which works just fine, but I'm curious if there's some other way.

Upvotes: 0

Views: 80

Answers (5)

evedovelli
evedovelli

Reputation: 2135

This is another way of doing it:

foo = ['a', 'b', 'c', 'd', 'e']
foo.inject({}){ |h,k| h[k] = k; h }

As suggested on comments, a better variations of this answer uses the each_with_object, so it gets rid off the trailing ; h:

foo.each_with_object({}) { |e,h| h[e]=e }

The advantage of either is that no intermediate array is constructed.

But the way you mentioned will work just fine:

Hash[foo.map{|a| [a, a]}]

Upvotes: 2

N N
N N

Reputation: 1638

I would try this:

foo  = ['a', 'b', 'c', 'd', 'e']
hash = Hash[foo.zip foo]

Upvotes: 0

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

foo = ['a', 'b', 'c', 'd', 'e']

[foo, foo].transpose.to_h
#=> {"a"=>"a", "b"=>"b", "c"=>"c", "d"=>"d", "e"=>"e"}

foo.zip(foo).to_h
#=> {"a"=>"a", "b"=>"b", "c"=>"c", "d"=>"d", "e"=>"e"}

Upvotes: 5

sawa
sawa

Reputation: 168269

Your issue does not make sense. I suspect it is an XY-problem. If you actually don't need to store the key-values in the hash, but just need to return the key back, then:

h = Hash.new{|_, k| k}
h["a"] # => "a"

Upvotes: 1

tadman
tadman

Reputation: 211740

Do you need a hash with just those values, or would a hash with a self-default be fine?

For example:

Hash.new { |h,k| h[k] = k }

You can also do this and combine it with itself into pairs:

Hash[foo.zip(foo)]

Upvotes: 3

Related Questions