【问题标题】:Recursively modify values in a nested hash递归修改嵌套哈希中的值
【发布时间】:2015-01-02 00:27:57
【问题描述】:

鉴于以下哈希结构,我想遍历该结构并使用“链接”键对所有值进行修改:

{"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。

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

干杯

【问题讨论】:

  • 我不明白你的问题。你到底想做什么?
  • 我已经更详细地更新了这个问题,希望对您有所帮助。
  • 如果您编辑以下内容会很有帮助: 1) 为您的哈希命名(例如,hash = {...}),以便读者可以在他们的答案中引用它; 2)将散列缩短并简化为您的问题所需的最低限度(这些术语不必与您的应用程序相关); 3)将散列重新格式化为不需要水平滚动来读取它(通过将它放在多行上); 4) 显示给定哈希的期望输出; 5) 清楚地说明你的问题。

标签: ruby-on-rails ruby recursion hash


【解决方案1】:

大概是这样的吧?

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

【讨论】:

  • 很好,但是如果有一个数字数组,它就会中断。
  • 考虑case v; when String; if k=="link"...end; when Hash; ... when Array; ... end
  • 该示例不包含数组数组,但您可能希望修改您的答案以包含这种可能性。关于@BroiSatse 的评论,我认为您可以将if k=="link" 更改为 if k.is_a? String &amp;&amp; k=="link"
  • @CarySwoveland 修复了多维数组问题。至于k.is_a? String &amp;&amp; k=="link",我认为k.is_a? String是多余的。
  • 啊,是的。很好地使用flatten。我已经把它藏起来了。
猜你喜欢
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
  • 2018-07-19
  • 2018-04-02
  • 2021-07-24
  • 2022-06-21
  • 2021-04-10
  • 2019-12-08
相关资源
最近更新 更多