我想在深层嵌套的哈希中插入uuids,并且我正在寻找在Ruby中执行此操作的方法。下面的代码显示了我在PHP中用于此任务的函数:
function insert_uuids(&$array)
{
if (!is_object($array) && !is_array($array)) {
return;
}
if (is_object($array)) {
$array->_uid = rand();
}
foreach ($array as &$subarray) {
$this->insert_uuids($subarray);
}
}
$this->insert_uuids($json);
// Gives me following result:
{
"component": "root",
"_uid": "3241242",
"body": [
{
"component": "headline",
"text": "42323",
"_uid": "343214556"
}
]
}
答案 0 :(得分:0)
我找到了解决方案。
my_hash = {
:title => "Home",
:layout => "body--rimless",
:content => {
:sections => [
{
:component => "section",
:style => "section--headed"
}
]
}
}
def insert_uuids(node)
if node.is_a?(Hash)
node[:_uid] = rand(100..9999)
node.each do |k,v|
if v.is_a?(Array)
v.each do |elm|
insert_uuids(elm)
end
elsif v.is_a?(Hash)
insert_uuids(v)
end
end
end
return node
end
puts insert_uuids(my_hash)
# {:title=>"Home", :layout=>"body--rimless", :content=>{:sections=>[{:component=>"section", :style=>"section--headed", :_uid=>9639}], :_uid=>570}, :_uid=>4972}
答案 1 :(得分:0)
你在要点中的Ruby示例有一些问题:
json
变量既不是JSON字符串也不是有效的Ruby Hash
is_a?(Hash)
或is_a?(Array)
,因为insert_uuids
方法仅定义在Hash
我会从这样的事情开始:
json = '{ "component": "root", "body": [{ "component": "headline", "text": "42323" }] }'
class Hash
def insert_uuids
subarrays = values.select { |value| value.is_a?(Array) }
subarrays.each do |array|
array.each do |element|
element.insert_uuids if element.respond_to?(:insert_uuids)
end
end
update('_uid' => 'some random uid')
end
end
require 'json'
hash = JSON.parse(json)
hash.insert_uuids
#=> {"component"=>"root", "body"=>[{"component"=>"headline", "text"=>"42323", "_uid"=>"some random uid"}], "_uid"=>"some random uid"}