[英]Recursively modify values in a nested hash
鑒於以下 hash 結構,我想遍歷該結構並使用“鏈接”鍵對所有值進行修改:
{"page_id":"12345", "link_data":{"message":"test message", "link":"https://www.example.com", "caption":"https://www.example.com", "child_attachments":[{"link":"http://www.example.com", "name":"test", "description":"test", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xap1/t45.1600-4/10736595_6021553533580_1924611765_n.png"}, {"link":"http://www.example.com", "name":"test", "description":"test", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xaf1/t45.1600-4/10736681_6021625991180_305087686_n.png"}, {"link":"http://www.example.com", "name":"test", "description":"test 2", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xfp1/t45.1600-4/10736569_6020761399780_1700219102_n.png"}]}}
我一直在使用的方法對我來說有點錯誤,因為我檢查了所有值以查看它們是否具有與應該是 URL 匹配的模式,然后在此時對其進行修改:
def find_all_values_for(key)
result = []
result << self[key]
self.values.each do |hash_value|
if hash_value.to_s =~ URI::regexp # if the value looks like a URL then change it
# update the url
end
end
end
因此,轉換的確切最終結果應該與 URL 修改后的 hash 相同。 我真正想做的是將跟蹤參數添加到 hash 中的每個 URL 中。
我玩弄了將 hash 轉換為字符串並對其執行一些字符串替換的想法,但這似乎不是做這種事情的最干凈的方法。
干杯
也許這樣的事情?
def update_links(hash)
hash.each do |k, v|
if k == "link" && v.is_a?(String)
# update link here
v.replace "a modification"
elsif v.is_a?(Hash)
update_links v
elsif v.is_a?(Array)
v.flatten.each { |x| update_links(x) if x.is_a?(Hash) }
end
end
hash
end
接受的答案在 ruby 2.5+ 中根本不起作用。 您不能就地修改 hash。 你會得到一個凍結的字符串錯誤:
`replace': can't modify frozen String: "..." (FrozenError)
相反,您可以使用修改后的鍵/值對創建一個新的 hash:
def update_links(hash)
hash.reduce({}) do |acc, (key,value)|
if value.is_a?(Hash)
acc[key.underscore] = update_links(value)
else
acc[key.underscore] = value
end
acc
end
end
在這個簡單的演示中,它強調了鍵,而沒有就地修改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.