ruby-on-rails - 递归修改嵌套哈希中的值

标签 ruby-on-rails ruby recursion 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 相同的散列。我真正想做的是将跟踪参数添加到哈希中的每个 URL。

我曾经考虑过将散列转换为字符串并对其执行一些字符串替换的想法,但这似乎不是做这种事情的最干净的方法。

干杯

最佳答案

也许是这样的?

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-on-rails - 递归修改嵌套哈希中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26763543/

相关文章:

ruby-on-rails - mimemagic 怎么了?

ruby-on-rails - 在heroku上运行时的ssh-agent问题

ruby - 比较哈希数组并打印预期结果和实际结果

ruby - Array#slice 的重叠等效项

ruby - 如何将方法作为字符串传递并调用它

c - 在 C 中打破递归的惯用方法是什么?

c - 数组元素乘法的二叉树方法

ruby-on-rails - to_xml 不适用于通过 Rails ActiveRecord habtm 引用返回的对象

ruby-on-rails - will_paginate 列表中每个项目的正确编号?

c++ - 递归问题求助C++