Module: HashWizard

Defined in:
lib/hash_wizard.rb,
lib/hash_wizard/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.delete_keys(hash_data, keys) ⇒ Object

method to exclude any key in entire nested hash including Array



6
7
8
9
10
11
12
# File 'lib/hash_wizard.rb', line 6

def self.delete_keys(hash_data, keys)
  case hash_data
  when Hash then hash_data = hash_data.each_with_object({}) { |(k, v), m| m[k] = delete_keys(v, keys) unless keys.include?(k); m }
  when Array then hash_data.map! { |e| delete_keys(e, keys) }
  end
  hash_data
end

.rename_key(hash_data, k_t_r, k_w_r) ⇒ Object

method to modify key with another in entire nested hash including Array k_t_r is key to replac and k_t_w is key to replace



16
17
18
19
20
21
22
# File 'lib/hash_wizard.rb', line 16

def self.rename_key(hash_data, k_t_r, k_w_r)
  case hash_data
  when Hash then hash_data = hash_data.inject({}) { |m, (k, v)| rename_key_block_code(m, k, v, k_t_r, k_w_r) }
  when Array then hash_data.map! { |e| rename_key(e, k_t_r, k_w_r) }
  end
  hash_data
end

.rename_key_block_code(m, k, v, k_t_r, k_w_r) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/hash_wizard.rb', line 24

def self.rename_key_block_code(m, k, v, k_t_r, k_w_r)
  if k == k_t_r
    m[k_w_r] = rename_key(v, k_t_r, k_w_r)
  else
    m[k] = rename_key(v, k_t_r, k_w_r)
  end
  m
end

.set_key_value(hash_data, key, value) ⇒ Object

method to set a particular value of a particuler key with another in entire nested hash including Array



34
35
36
37
38
39
40
# File 'lib/hash_wizard.rb', line 34

def self.set_key_value(hash_data, key, value)
  case hash_data
  when Hash then hash_data = hash_data.inject({}) { |m, (k, v)| set_key_value_block_code(m, k, v, key, value) }
  when Array then hash_data.map! { |e| set_key_value(e, key, value) }
  end
  hash_data
end

.set_key_value_block_code(m, k, v, key, value) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/hash_wizard.rb', line 42

def self.set_key_value_block_code(m, k, v, key, value)
  m[k] = if k == key && m[k].nil?
    value
  else
    set_key_value(v, key, value)
  end
  m
end