目前我有类似的东西:
arr = [
:name,
:address,
cards_attributes: [
:last_name,
:first_name,
phones_attributes: [
:number,
:_destroy
],
emails_attributes: [
:number,
:_destroy
],
...
]
]
...我想把它变成类似这样的东西:
arr = [
:id, # <- new!
:name,
:address,
cards_attributes: [
:id, # <- new!
:last_name,
:first_name,
phones_attributes: [
:id, # <- new!
:number,
:_destroy
],
emails_attributes: [
:id, # <- new!
:number,
:_destroy
],
...
]
]
我知道我可以使用 arr.push(:id)
将新符号添加到第一级,但如何将元素添加到子哈希中?
最佳答案
def add_id(collection)
collection.unshift(:id) if collection.respond_to?(:unshift)
collection.each do |key, value|
add_id(key) if key.respond_to?(:each)
add_id(value) if value.respond_to?(:each)
end
end
编辑:对于以下更新
"My question was actually more about how to elegantly access the sub hashes?"
我们可以使用相同的总体思路。由于您没有指定要在哈希上执行的操作,因此该方法将需要一个 block :
def traverse(collection)
yield collection if collection.is_a? Hash
collection.each do |key, value|
traverse(key) if key.respond_to?(:each)
traverse(value) if value.respond_to?(:each)
end
end
traverse(arr) { |hash| puts hash }
关于arrays - 修改符号的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34831580/