cga*_*her 6 ruby recursion hash ruby-on-rails
给定以下哈希结构,我想走结构并使用"link"键修改所有值:
{"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"}]}}
Run Code Online (Sandbox Code Playgroud)
我一直在玩的方法对我来说感觉有点不对,我要检查所有值,看看它们是否有匹配应该是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
Run Code Online (Sandbox Code Playgroud)
因此,转换的确切最终结果应该与URL的修改相同.我真正想要做的是将跟踪参数添加到散列中的每个URL.
我已经玩弄了将哈希转换为字符串并在其上执行一些字符串替换的想法,但这似乎不是这种做事最干净的方法.
干杯
Aug*_*ust 12
也许这样的事情?
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
Run Code Online (Sandbox Code Playgroud)