加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:49:24 所属栏目:百科 来源:网络整理
导读:给定以下哈希结构,我想走结构并使用“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","na
给定以下哈希结构,我想走结构并使用“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","picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xaf1/t45.1600-4/10736681_6021625991180_305087686_n.png"},"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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读