递归函数以检索深度嵌套的哈希

时间:2018-08-09 14:43:37

标签: ruby

我有以下代码:

ATTRIBUTES_TO_ANONYMIZE = [ { submitted_input: [:salutation, { user_location: [:city, :country, :full_address] }] }]

  def runner
    anonymize_data_hash(ATTRIBUTES_TO_ANONYMIZE)
  end

  def anonymize_data_hash(data, key=nil)
    if data.is_a?(Hash)
      data.each do |key, value|
        anonymize_data_hash(value, key)
      end
    elsif data.is_a?(Array)
      data.each do |value|
        anonymize_data_hash(value, key)
      end
    else
      puts "#{key}[#{data}]"
    end
  end

这将产生以下输出:

submitted_input[salutation]
user_location[city]
user_location[country]
user_location[full_address]

我真正需要的输出是:

submitted_input[salutation]
submitted_input[user_location][city]
submitted_input[user_location][country]
submitted_input[user_location][full_address]

有人知道我如何实现此输出。任何帮助都将受到高度赞赏

1 个答案:

答案 0 :(得分:0)

在递归调用中,请跟踪嵌套,而不仅仅是转发最后一个哈希中的键。

  def anonymize_data_hash(data, path=[])
    if data.is_a?(Hash)
      data.each do |key, value|
        anonymize_data_hash(value, path + [key])
      end
    elsif data.is_a?(Array)
      data.each do |value|
        anonymize_data_hash(value, path)
      end
    else
      path = path.clone
      key = path.shift
      path = (path + [data]).map{|x| "[#{x}]"}.join
      puts "#{key}#{path}"
    end
  end