Class: Hash

Inherits:
Object show all
Defined in:
lib/ruby_smart/support/core_ext/ruby/hash.rb,
lib/ruby_smart/support/core_ext/ruby/hash.rb,
lib/ruby_smart/support/core_ext/activesupport/hash.rb,
lib/ruby_smart/support/core_ext/activesupport/hash.rb,
lib/ruby_smart/support/core_ext/activesupport/hash.rb

Instance Method Summary collapse

Instance Method Details

#deep_reject(&blk) ⇒ Object

returns a new Hash with items that the block evaluates to true removed, also to deep Hashes.



48
49
50
# File 'lib/ruby_smart/support/core_ext/activesupport/hash.rb', line 48

def deep_reject(&blk)
  deep_dup.deep_reject!(&blk)
end

#deep_reject!(&blk) ⇒ Object

deep reject by provided block deep remove keys that the block evaluates to true

Examples:

hsh = {a: 1, b: 2, c: 3, d: {a: 1, b: 2, c: 3}}
hsh.deep_reject! {|_k,v| v.is_a?(Numeric) && v > 2}
> hsh == {a: 1, b: 2, d: {a: 1, b: 2}}

hsh = {a: 1, b: 2, c: 3, d: {a: 1, b: 2, c: 3}}
hsh.deep_reject! {|k,v| k == :d || v == 2}
> hsh == {a: 1, c: 3}


63
64
65
66
67
68
69
70
71
# File 'lib/ruby_smart/support/core_ext/activesupport/hash.rb', line 63

def deep_reject!(&blk)
  each do |k, v|
    if blk.(k, v)
      delete(k)
    elsif v.is_a?(Hash)
      v.deep_reject!(&blk)
    end
  end
end

#only!(*keys) ⇒ Hash

Replaces the hash with only the given keys (if exists), but returns the same hash (not the removed keys - this differs to Hash#slice!)

Examples:

hsh = {a: 1, b: 2, c: 3}
hsh.only!(:a, :d)
> {a: 1}
> hsh == {a: 1}

Parameters:

Returns:



19
20
21
22
# File 'lib/ruby_smart/support/core_ext/activesupport/hash.rb', line 19

def only!(*keys)
  slice!(*keys)
  self
end

#productArray

creates a 'product' of all values per existing key as a combination

hash = { first: [:a,:b], second: [:x,:c]}

[:second=>:x, :second=>:c, :second=>:x, :second=>:c]

Returns:

  • (Array)

    combinations



22
23
24
25
# File 'lib/ruby_smart/support/core_ext/ruby/hash.rb', line 22

def product
  product = values[0].product(*values[1..-1])
  product.map{|p| Hash[keys.zip p]}
end

#to_md5String

returns the md5 of any hash by using the +#inspect+ method

Returns:



7
8
9
# File 'lib/ruby_smart/support/core_ext/ruby/hash.rb', line 7

def to_md5
  Digest::MD5.hexdigest(Hash[self.sort].inspect)
end

#without!(*keys) ⇒ Hash

removes the given keys from hash and returns those key => value pairs (this differs to Hash#except!)

Examples:

hsh = {a: 1, b: 2, c: 3}
hsh.without!(:a, :d)
> {a: 1}
> hsh == {b: 2, c: 3}

Parameters:

Returns:



39
40
41
# File 'lib/ruby_smart/support/core_ext/activesupport/hash.rb', line 39

def without!(*keys)
  Hash[to_a - except!(*keys).to_a]
end