Victor Ronin
Victor Ronin

Reputation: 23268

Use array as keys and generate values to produce a hash

I have an array. As example:

a = ["foo", "bar", "baz"]

I want to convert it to a hash:

h = { "foo" => randomvalue1, "bar" => randomvalue2, "baz" => randomvalue3 }

I come up with following way:

Hash[* a.map { |value| [value, randomvalue_generator] }.flatten]

My experience with Ruby quite limited, but have a feeling that there should be simler way of doing this. Mainly, I am interested in reducing code complexity.

Upvotes: 1

Views: 56

Answers (1)

Kyle
Kyle

Reputation: 22258

Your way is fine except you do not need to flatten or splat

a = ["foo", "bar","baz"]
Hash[a.map{ |k| [k, rand(5)] }]
# {"foo"=>1, "bar"=>0, "baz"=>2} 

There many other ways to accomplish this but I like your original solution.

a.each_with_object({}){ |k, h| h[k] = rand(5) }

a.inject({}){ |h, k| h[k] = rand(5); h }

a.inject({}){ |h, k| h.merge k => rand(5) }

Hash[a.zip a.map{ |_| rand(5) }]

Upvotes: 1

Related Questions