1

我有一个 Ruby 数组,其元素在字符串和哈希之间交替。例如-

["1234", Hash#1, "5678", Hash#2]

我想从中创建一个嵌套的哈希结构。所以,

hash["1234"]["key in hash#1"] = value
hash["5678"]["key in hash#2"] = value

有没有人/现在有这样做的好方法?谢谢你。

4

4 回答 4

7

只需使用

hsh = Hash[*arr] #suppose arr is the array you have

它将一次切片 2 并转换为哈希。

于 2012-05-22T15:58:44.680 回答
3

我不认为数组上有一种方法可以直接执行此操作。以下代码有效并且很容易阅读。

hsh = {}

ary.each_slice(2) do |a, b|
  hsh[a] = b
end

# Now `hsh` is as you want it to be
于 2012-05-22T15:44:04.577 回答
1

让我们猜测一下,使用构面只是为了好玩:

require 'facets'
xs = ["1234", {:a => 1, :b => 2}, "5678", {:c => 3}]
xs.each_slice(2).mash.to_h
#=> {"1234"=>{:a=>1, :b=>2}, "5678"=>{:c=>3}}
于 2012-05-22T15:52:59.010 回答
1

猜测您想要什么,因为“哈希#1中的键”根本不清楚,您也没有定义hashvalue应该是什么:

value = 42

h1 = {a:1}
h2 = {b:2}
a = ["1234",h1,"5678",h2]
a.each_slice(2).each{ |str,h| h[str] = value }
p h1, #=> {:a=>1, "1234"=>42}
  h2  #=> {:b=>2, "5678"=>42}

或者,也许您的意思是:

h1 = {a:1}
h2 = {b:2}
a = ["1234",h1,"5678",h2]

hash = Hash[ a.each_slice(2).to_a ]
p hash             #=> {"1234"=>{:a=>1}, "5678"=>{:b=>2}}
p hash["1234"][:a] #=> 1
于 2012-05-22T15:49:04.597 回答