将数组元素转换为哈希红宝石

时间:2019-12-26 23:22:36

标签: arrays ruby hash

我有一个字符串数组,想要将其转换为哈希,其中 array[0]是键,array[1]是值,然后array[2]是下一组键。

我已经尝试以各种组合方式尝试#each#map#each_with_object#to_h,而我能得到的最接近的结果是将每个数组元素设置为零值。

# 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
    }

3 个答案:

答案 0 :(得分:7)

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

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

请参见Hash::[]

Hash[*arr]与此处相同:

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

答案 1 :(得分:2)

您可以使用Enumerable#each_slice将数组分为几对,然后将每对的第一项用作键,第二项用作值。

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 }

答案 2 :(得分:0)

即使我会建议亚历克斯·韦恩(Alex Wayne)回答,也有另一种方法可以解决此问题:

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