0

我需要解析并显示以 JSON 或 Ruby 形式返回的 solr 方面:

集合: [ "a", 1, "b", 2, "c", 3, "d", 4, ... ]

进入

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

最干净的方法是什么?

4

2 回答 2

2

编辑:现在我们知道你真正想要什么,一个hash......

collections = ["a", 1, "b", 2, "c", 3, "d", 4]
Hash[*collections]
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4} 

原始答案:我可能不明白你的目标,但......

collections = ["a", 1, "b", 2, "c", 3, "d", 4]
collections.each_slice(2).map{ |(x, y)| "#{x} - #{y}" }
# => ["a - 1", "b - 2", "c - 3", "d - 4"]
于 2012-09-12T20:41:31.713 回答
1

我看到你想做的可能是哈希?{a => "1", b => "2"} ??

如果是这样,请阅读以下内容:

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


result = Hash[*collections.flatten]

result prints {"a"=>1, "b"=>2, "c"=>3, "d"=>4} 
于 2012-09-12T20:52:52.287 回答