Class: Hash

Inherits:
Object show all
Defined in:
lib/jss/compatibility.rb,
lib/jss/ruby_extensions/hash.rb

Instance Method Summary collapse

Instance Method Details

#jss_nillify!(to_nils = '', recurse = false) {|value| ... } ⇒ Hash

Convert Hash values to nil.

With no block, values equalling the String, or any member of the Array, given will be converted to nil. Equality is evaluated with == and Array#include?

With a block, if the result of the block evaluates to true, the value is converted to nil.

Subhashes are ignored unless recurse is true.

Examples:

hash = {:foo => '', :bar => {:baz => '' }}
hash.jss_nillify!  # {:foo => nil, :bar => {:baz => '' }}

hash = {:foo => '', :bar => {:baz => '' }}
hash.jss_nillify! '', :recurse  # {:foo => nil, :bar => {:baz => nil }}

hash = {:foo => 123, :bar => {:baz => '', :bim => "123" }}
hash.jss_nillify! ['', 123], :recurse # {:foo => nil, :bar => {:baz => nil, :bim => "123" }}

hash = {:foo => 123, :bar => {:baz => '', :bim => "123" }}
hash.jss_nillify!(:anything, :recurse){|v| v.to_i == 123 }  # {:foo => nil, :bar => {:baz => '', :bim => nil }}

Parameters:

  • to_nils (String, Array) (defaults to: '')

    Hash values equal to (==) these become nil. Defaults to empty string

  • recurse (Boolean) (defaults to: false)

    should sub-Hashes be nillified?

Yields:

  • (value)

    Hash values for which the block returns true will become nil.

Returns:

  • (Hash)

    the hash with the desired values converted to nil



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/jss/ruby_extensions/hash.rb', line 60

def jss_nillify!(to_nils = '', recurse = false, &block )

  nillify_these = [] << to_nils
  nillify_these.flatten!

  self.each_pair do |k,v|
    if v.class == Hash
      v.jss_nillify!(to_nils, recurse, &block)
      next
    end
    do_it = if block_given?
      yield v
    else
      nillify_these.include? v
    end
    self[k] = nil if do_it
  end # each pair
end