如何仅在第一次出现时深度转换 hash/array 中的键或值

How can I deep transform key or value in a hash/array only for the first occurence

我有下面的例子

 input = {
    "books2" => [1, {a: 1, b: "seller35" }],
    "books3" => { "a" =>[{"5.5"=>"seller35", "6.5" => "foo"}]}
    }

而且我想对匹配 seller35 的值进行深度转换。但是,仅限于第一次出现。所以对于 b: "seller35""5.5"=>"seller35" 应该保持完整。

理想情况下,对于键,值 and/or 数组中的元素。

我查看了:https://apidock.com/rails/v6.0.0/Hash/_deep_transform_keys_in_object 寻找灵感,但找不到解决方案。这对所有人都有效

input.deep_transform_values { |value| value == "seller35" ? "" : value }
=> {"books2"=>[1, {:a=>1, :b=>""}], "books3"=>{"a"=>[{"5.5"=>"", "6.5"=>"foo"}]}}

谢谢!

您可以创建一个 done 布尔值来跟踪替换是否已经完成,并且 return 来自块的适当值:

require "active_support/core_ext/hash/deep_transform_values"

def deep_transform_values_once(hash:, old_value:, new_value:)
  done = false
  hash.deep_transform_values do |value|
    if !done && value == old_value
      done = true
      new_value
    else
      value
    end
  end
end

input = {
  "books2" => [1, { a: 1, b: "seller35" }],
  "books3" => { "a" => [{ "5.5" => "seller35", "6.5" => "foo" }] },
}

p deep_transform_values_once(hash: input, old_value: "seller35", new_value: "")

输出:

{"books2"=>[1, {:a=>1, :b=>""}], "books3"=>{"a"=>[{"5.5"=>"seller35", "6.5"=>"foo"}]}}