简体   繁体   中英

Ruby : hydrate hash values from array

Let's say I have an ruby array like this :

values = ['val_a', 'val_b',..., 'val_z'] # 26 values

And an hash with keys

hash = {a: nil, b: nil, ... , z: nil} # 26 keys

I know that the array is sorted, and I know that keys of hash are sorted, and I know both array and hash are of same size.

How can I elegantly hydrate hash values so that I end up with

{a: 'val_a', b: 'val_b', ... , z: 'val_z'}
hash_with_values = hash.keys.zip(values).to_h

Note that in some (most?) languages, keys of hashes/maps are unordered, so that would not work. That was also the case for Ruby < 1.9, but, from then on, they are guaranteed to be ordered (insertion order).

Since Ruby 2.4.0 you can do the following:

hash.transform_values.with_index { |v,i| values[i] }

Using Hash#transform_values , the intent is clear. Its dangerous counterpart Hash#transform_values! is also available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM