Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a hash from an array of keys

Tags:

arrays

ruby

hash

I have looked at other questions in SO and did not find an answer for my specific problem.

I have an array:

a = ["a", "b", "c", "d"] 

I want to convert this array to a hash where the array elements become the keys in the hash and all they the same value say 1. i.e hash should be:

{"a" => 1, "b" => 1, "c" => 1, "d" => 1} 
like image 756
Dennis Mathews Avatar asked Mar 10 '12 18:03

Dennis Mathews


People also ask

How do you turn an array into a hash?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

How do I create a hash from two arrays in Perl?

You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.

How do I assign an array to a hash in Perl?

To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value. When inverted, you end up with a hash that has many values for the same key.


2 Answers

My solution, one among the others :-)

a = ["a", "b", "c", "d"] h = Hash[a.map {|x| [x, 1]}] 
like image 128
Baldrick Avatar answered Oct 15 '22 14:10

Baldrick


There are several options:

  • to_h with block:

    a.to_h { |a_i| [a_i, 1] } #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1} 
  • product + to_h:

    a.product([1]).to_h #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1} 
  • transpose + to_h:

    [a,[1] * a.size].transpose.to_h #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1} 
like image 45
potashin Avatar answered Oct 15 '22 16:10

potashin