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}
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.
You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.
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.
My solution, one among the others :-)
a = ["a", "b", "c", "d"] h = Hash[a.map {|x| [x, 1]}]
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With