ruby 从散列中递归删除'nil'和空值

00jrzges  于 2022-12-29  发布在  Ruby
关注(0)|答案(3)|浏览(128)

我有一个散列,开头是:

{"request"=>{
  "security"=>{"username"=>{"type"=>nil}, "password"=>{"type"=>nil}},
  "order_i_d"=>{"type"=>nil, "description"=>nil},
  "order_number"=>{"type"=>nil},
  "show_kit_as_individual_s_k_us"=>false,
  "website_i_d"=>{"type"=>nil, "description"=>nil}
}}

我想递归地删除所有nil?empty?的值,但保留falsey的值。

{"request"=>{
  "show_kit_as_individual_s_k_us"=>false
}}

我怎样才能做到这一点?

vngu2lb8

vngu2lb81#

这只是另一个实现,编写的目的是为了好玩和练习。

  • 无猴修补
  • 适用于哈希和数组
  • 可用作模块函数,如:第一个月
  • 也是一个破坏性的目标修改变体:DeepCompact.deep_compact!(hash)
  • 可通过在现有对象上扩展来使用:{ foo: nil }.extend(DeepCompact).deep_compact
  • 可通过细化使用:将using DeepCompact添加到文件/类将使deep_compactdeep_compact!成为该文件/类中所有代码的散列和数组。

以下是该模块:

module DeepCompact
  [Hash, Array].each do |klass|
    refine klass do
      def deep_compact
        DeepCompact.deep_compact(self)
      end

      def deep_compact!
        DeepCompact.deep_compact!(self)
      end
    end
  end

  def self.extended(where)
    where.instance_exec do
      def deep_compact
        DeepCompact.deep_compact(self)
      end

      def deep_compact!
        DeepCompact.deep_compact!(self)
      end
    end
  end

  def deep_compact(obj)
    case obj
    when Hash
      obj.each_with_object({}) do |(key, val), obj|
        new_val = DeepCompact.deep_compact(val)
        next if new_val.nil? || (new_val.respond_to?(:empty?) && new_val.empty?)
        obj[key] = new_val
      end
    when Array
      obj.each_with_object([]) do |val, obj|
        new_val = DeepCompact.deep_compact(val)
        next if new_val.nil? || (new_val.respond_to?(:empty?) && new_val.empty?)
        obj << new_val
      end
    else
      obj
    end
  end
  module_function :deep_compact

  def deep_compact!(obj)
    case obj
    when Hash
      obj.delete_if do |_, val|
        val.nil? || (val.respond_to?(:empty?) && val.empty?) || DeepCompact.deep_compact!(val)
      end
      obj.empty?
    when Array
      obj.delete_if do |val|
        val.nil? || (val.respond_to?(:empty?) && val.empty?) || DeepCompact.deep_compact!(val)
      end
      obj.empty?
    else
      false
    end
  end
  module_function :deep_compact!
end

下面是一些如何使用它的例子:

hsh = {
  'hello' => [
    'world',
    { 'and' => nil }
  ],
  'greetings' => nil,
  'salutations' => {
    'to' => { 'you' => true, 'him' => 'yes', 'her' => nil },
     'but_not_to' => nil
  }
}

puts "Original:"
pp hsh
puts
puts "Non-destructive module function:"
pp DeepCompact.deep_compact(hsh)
puts
hsh.extend(DeepCompact)
puts "Non-destructive after hash extended:"
pp hsh.deep_compact
puts
puts "Destructive refinement for array:"
array = [hsh]
using DeepCompact
array.deep_compact!
pp array

并且输出:

Original:
{"hello"=>["world", {"and"=>nil}],
 "greetings"=>nil,
 "salutations"=>
  {"to"=>{"you"=>true, "him"=>"yes", "her"=>nil}, "but_not_to"=>nil}}

Non-destructive module function:
{"hello"=>["world"], "salutations"=>{"to"=>{"you"=>true, "him"=>"yes"}}}

Non-destructive after hash extended:
{"hello"=>["world"], "salutations"=>{"to"=>{"you"=>true, "him"=>"yes"}}}

Destructive refinement for array:
[{"hello"=>["world"], "salutations"=>{"to"=>{"you"=>true, "him"=>"yes"}}}]

或者只是使用多个宝石,为您提供这一点之一。

2skhul33

2skhul332#

得出以下结论:

class Hash  
  def deep_compact!
    self.each_pair do |key, value|
      if value.is_a?(Hash)
        value.deep_compact!
      end
      if value.nil? || (value.is_a?(Hash) && value.empty?)
        self.delete(key)
      end
    end
  end
end
rbl8hiat

rbl8hiat3#

另一种选择:

class Hash
    def deep_transform(&block)
      self.inject({}){|result, (key,value)|
        value = if Hash === value
                  value.deep_transform(&block)
                else
                  value
                end
        block.call(result,key,value)
        result
      }
    end

    def deep_compact
      self.deep_transform do |result, key, value|
        if value.nil? || (value.is_a?(Hash) && value.empty?)
          # Don't Keep
        else
          result[key] = value
        end
      end
    end
end

相关问题