我有一个像这样的数组:
[
[0] {
"Success" => true
},
[1] {
"Success" => true
},
[2] {
"Success" => true
},
[3] {
"Success" => true
}
]
上面的每个数字都有一个与之相关的更大的多维数组,但这不是我目前关注的问题。我想用新的键值重命名数字[0..3]。
所以它看起来像这样
[
["pop"] {
"Success" => true
},
["rock"] {
"Success" => true
},
["country"] {
"Success" => true
},
["soul/r&b"] {
"Success" => true
}
]
提前致谢!
答案 0 :(得分:1)
如果你的输入真的是JSON,你需要首先解析JSON并将其转换为Ruby数据结构:
require 'active_support'
json = "[[0,{\"Success\":true}],[1,{\"Success\":true}],[2,{\"Success\":true}],[3,{\"Success\":true}]]"
array = ActiveSupport::JSON.decode( json )
=> [ [0, { "Success" => true }], [1, { "Success" => true }], [2, { "Success" => true }], [3, { "Success" => true }] ]
现在您的输入是Ruby数组......
我假设您将新密钥存储在数组中,如下所示:
new_keys = %w{pop rock country soul/r&b}
=> ["pop", "rock", "country", "soul/r&b"]
下一步是用新密钥替换JSON数组中每个子数组的第一个元素:
result = Array.new
array.each do |value|
i, rest = value
result << [ new_keys[i], rest ]
end
json = result.to_json
=> "[[\"pop\",{\"Success\":true}],
[\"rock\",{\"Success\":true}],
[\"country\",{\"Success\":true}],
[\"soul/r&b\",{\"Success\":true}]]"
答案 1 :(得分:0)
Ruby中有两个类似于数据结构的数组:存储可由整数索引访问的有序数据的数组和散列,散列是存储可由某个关键对象(例如字符串)访问的数据的散列映射。虽然它们的访问方式相似,但它们是不同的类。
从您的代码(无效的ruby btw。)我猜你有以下数据结构:
array = [
{ "Success" => true },
{ "Success" => true },
{ "Success" => true },
{ "Success" => true }
]
可以通过以下代码转移:
keys = ["pop", "rock", "country", "soul/r&b"]
result = {}
keys.each_with_index {|key, i| result[index] = array[i]}
这导致以下数据结构。它是一个哈希,包含原始数组的元素(它们自己是哈希值)作为值。
{
"pop" => { "Success" => true },
"rock" => { "Success" => true },
"country" => { "Success" => true },
"soul/r&b" => { "Success" => true }
}
答案 2 :(得分:0)
styles = {0: "pop", 1: "rock", 2: "country", 3: "shoul/r&b"}
info2 = Hash[info.map { |index, h| [[styles[index]], h}]