codescribble
codescribble

Reputation: 67

Create a hash dynamically and assign each key a different value

How can I dynamically create a hash, giving each of its key a different value? For example:

hash = {}
(1..9).each{|key| hash[key] = ' '}

creates a hash with keys 1 to 9, where every key has the same value, a space. How can I do the same, keys 1 to 9, but with each key holding a different value.

Upvotes: 0

Views: 2521

Answers (3)

steenslag
steenslag

Reputation: 80065

p (1..9).zip(("a".."i").to_a.shuffle).to_h
# => {1=>"a", 2=>"d", 3=>"b", 4=>"h", 5=>"e", 6=>"g", 7=>"f", 8=>"i", 9=>"c"}

Upvotes: 1

Bijendra
Bijendra

Reputation: 10015

You can use this for dynamic hash creation with distinct key values.

hash = {}
(1..9).each_with_index{|key,index| hash[key] = index}
1..9
>> hash

hash
{1=>0, 2=>1, 3=>2, 4=>3, 5=>4, 6=>5, 7=>6, 8=>7, 9=>8}

Upvotes: 1

undur_gongor
undur_gongor

Reputation: 15954

If the values do not matter and just have to be different:

hash = Hash[(1..9).zip(1..9)]   
# => {1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9}

hash = Hash[(1..9).zip('a'..'z')]   
# => {1=>"a", 2=>"b", 3=>"c", 4=>"d", 5=>"e", 6=>"f", 7=>"g", 8=>"h", 9=>"i"}

For bigger hashes, performance can be improved by not creating intermediate arrays:

hash = (1..1000).inject({}) { | a, e | a[e] = e; a }

Upvotes: 1

Related Questions