在Ruby中将数组转换为哈希的最佳方法是什么

时间:2020-03-05 18:46:27  来源:igfitidea点击:

在Ruby中,以下列形式之一给出数组:

[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]

...将其转换为哈希形式的最佳方法是...

{apple => 1, banana => 2}

解决方案

回答

只需使用Hash [* array_variable.flatten]`

例如:

a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"

a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"

使用Array#flatten(1)限制了递归,因此Array键和值可以按预期工作。

回答

Edit: Saw the responses posted while I was writing, Hash[a.flatten] seems the way to go.
  Must have missed that bit in the documentation when I was thinking through the response. Thought the solutions that I've written can be used as alternatives if required.

第二种形式更简单:

a = [[:apple, 1], [:banana, 2]]
h = a.inject({}) { |r, i| r[i.first] = i.last; r }

a =数组,h =哈希,r =返回值哈希(我们在其中累加的哈希值),i =数组中的项

我想到的第一种形式的最简洁的方式是这样的:

a = [:apple, 1, :banana, 2]
h = {}
a.each_slice(2) { |i| h[i.first] = i.last }

回答

不知道这是否是最好的方法,但这可以工作:

a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
  m1[a[x*2]] = a[x*2 + 1]
end

b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
  m2[x] = y
end

回答

如果数值是seq索引,那么我们可以有更简单的方法...
这是我的代码提交,我的Ruby有点生锈

input = ["cat", 1, "dog", 2, "wombat", 3]
   hash = Hash.new
   input.each_with_index {|item, index|
     if (index%2 == 0) hash[item] = input[index+1]
   }
   hash   #=> {"cat"=>1, "wombat"=>3, "dog"=>2}

回答

追加答案,但使用匿名数组并注释:

Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]

从内部开始,将答案分开:

  • 实际上," a,b,c,d"是一个字符串。
  • 将逗号分割成一个数组。
  • zip和以下数组。
  • [1,2,3,4]是一个实际的数组。

中间结果是:

[[a,1],[b,2],[c,3],[d,4]]

展平然后将其转换为:

["a",1,"b",2,"c",3,"d",4]

接着:

* [" a",1," b",2," c",3," d",4]将其展开为
" a",1," b",2," c",3," d",4

我们可以将其用作" Hash []"方法的参数:

Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]

产生:

{"a"=>1, "b"=>2, "c"=>3, "d"=>4}