简体   繁体   中英

create a hash from an array in ruby

I have an array in a specific order, and wish to create a hash with the odd numbered entries of the array as indexes and the even as values. This code does it perfectly, but leaves out one pair of values from the array.

    resolv_hash = Hash[*namerslv_array]
            puts "values in hash"
            resolv_hash.each do |key, array|
            puts "#{key}   " + array
            end

can anyone help with this please?

I think you want:

resolv_hash = namerslv_array.each_slice(2).to_h

Illustration:

>> array = [1,2,3,4,5,6,7,8,9,0]
>> array.each_slice(2).to_h
=> {1=>2, 3=>4, 5=>6, 7=>8, 9=>0}

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