【问题标题】:how do I substitute elements in a hash using ruby?如何使用 ruby​​ 替换散列中的元素?
【发布时间】:2016-04-06 01:07:31
【问题描述】:

我有不确定的键名和字段值的 JSON 哈希,我想用这些值替换字符串或子字符串。例如:

{"COLLECTION"=>{"$"=>"biblestudy"}, "JSON"=>{"$"=>"{ \"type\" : \"reaction\", \"verse_reaction\": \"That our lives should be one of giving life\", \"verse_key\" : \"109dc58b8020681e\" }"}, "KEY"=>{"$"=>"key.verse_reaction"}, "REPLACE-KEY"=>{"$"=>"replace-key"}}

我可能想用存储在 a 中的某个值替换 replace-key {"replace-key" : "this is the replacement"}

我尝试了以下方法:

json_element.map { |k,v| v.map { |k1,v1| v1.replace_hash(hash={"hope" => "life" })} }

我创建了replace_hash 作为String 的方法:

 def replace_hash(hash=nil)

  if hash.present?

    hash.each do | key, substitute |

      self.sub! key, substitute
    end

  end

【问题讨论】:

    标签: ruby json hash substitution


    【解决方案1】:

    json_element.map { |k,v| v['$'].replace_hash(hash = @replace_hash) }

    我玩弄了上面的方法并让它工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 2016-11-04
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      相关资源
      最近更新 更多