Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn an array into keys for hash

Tags:

arrays

ruby

hash

How do I turn an Array into a Hash with values of 0 without an each loop.

For example, given this array:

[1, 2, 3, 4]

I want to get this hash:

{"1"=>0, "2"=>0, "3"=>0, "4"=>0}
like image 588
San Backups Avatar asked Jul 29 '26 13:07

San Backups


2 Answers

The standard approach is Hash[...]:

Hash[xs.map { |x| [x.to_s, 0] }]

Or Enumerable#mash if you happen to use Facets. I cannot think of something more concise and declarative:

xs.mash { |x| [x.to_s, 0] }
like image 100
tokland Avatar answered Jul 31 '26 07:07

tokland


array.inject({}) { | a, e | a[e.to_s] = 0; a }

or in a more clean way (thanks to tokland, see the discussion in the comments)

array.inject({}) { | a, e | a.update(e.to_s => 0) }
like image 41
undur_gongor Avatar answered Jul 31 '26 07:07

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!