Gen Forsythe
Gen Forsythe

Reputation: 11

Convert an array elements into a hash ruby

I have an array of strings and want to convert it into a hash where array[0] is the key and array[1] is the value then array[2] is the key for the next set.

I have tried #each, #map, #each_with_object, #to_h in all manner of combinations and the closest I can get is to set each array element to a key with nil value.

# animal_data1 ={}
# animal_data1 = Hash[collected.map {|key,value| [key.to_sym, value]}]
# puts animal_data1 

=> {
    :"Kingdom:Five groups that classify all living things"=>nil,
    :Animalia=>nil,
    :"Phylum:A group of animals within the animal kingdom"=>nil,
    :Chordata=>nil,
    :"Class:A group of animals within a pylum"=>nil,
    :Mammalia=>nil,
    :"Order:A group of animals within a class"=>nil,
    :Tubulidentata=>nil,
    :"Family:A group of animals within an order"=>nil
    }

Upvotes: 1

Views: 123

Answers (3)

Adem Dinarević
Adem Dinarević

Reputation: 185

Even though I would suggest Alex Wayne's answer, there is another way you can approach this:

array = [1,2,3,4,5,6,7,8,9,10] 
hash = {}
i = 0

while (i<array.length)
  hash[array[i] = array[i+1]
  i+=2
end

hash

Sample demo

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

arr = [:a, :b, :c, :d]

Hash[*arr]
  #=> {:a=>:b, :c=>:d}

See Hash::[].

Hash[*arr] is here the same as:

Hash[:a, :b, :c, :d]

Upvotes: 7

Alex Wayne
Alex Wayne

Reputation: 187034

You can use Enumerable#each_slice to group the array into pairs, then use the first item of each pair as the key, and the second item as the value.

def array_to_hash(array)
  # Create a new hash to store the return value
  hash = {}

  # Slice the array into smaller arrays, each of length 2.
  array.each_slice(2) do |pair|

    # Get the key and value from the pair
    key = pair[0]
    value = pair[1]

    # Update the hash
    hash[key] = value
  end

  # Return the hash
  hash
end

array_to_hash([:a, :b, :c, :d]) #=> { :a => :b, :c => :d }

Upvotes: 2

Related Questions