1

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?

1 Answer 1

3

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}
Sign up to request clarification or add additional context in comments.

2 Comments

That works, but still misses a pair or entries... my code output gives * file[/etc/resolv.conf] action create_if_missing (up to date) * aix_etcresolv[nameserver] action add values in array nameserver 192.10.201.1 domain abc.aus.century.com nameserver 176.111.1.1 values in hash nameserver 176.111.1.1 domain abc.aus.century.com where my file contents is cat /etc/resolv.conf nameserver 192.10.201.1 domain abc.aus.century.com nameserver 176.111.1.1
Yes, that would do it. Keys are by definition unique, so trying to add an element to a Hash with an existing key instead results in replacement of that key's value with the new value. If you need duplicate keys/first values, you could use namerslv_array.each_slice(2) and store your data as array pairs instead of a hash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.