简体   繁体   中英

Ruby on Rails ActiveSupport or plain Ruby way of merging arrays into a hash

What's a smart way of using ActiveSupport or perhaps regular built in Ruby functionality to take two arrays and merge them into a hash where each element in an array matches the element in a parallel array? imagine two arrays:

names = ["Danny", "Johnny"]
ages = ["25", "32"]

The end result should be a hash that looks like:

{"Danny" => "25", "Johnny" => "32"}

If you're using ruby 1.8.7 or above:

Hash[names.zip ages]

or for 1.8.6:

Hash[*names.zip(ages).flatten]

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