Class: Hash

Inherits:
Object show all
Defined in:
lib/lite/ruby/hash.rb,
lib/lite/ruby/safe/hash.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.zip(keys, values) ⇒ Object



10
11
12
# File 'lib/lite/ruby/hash.rb', line 10

def zip(keys, values)
  keys.size.times.with_object({}) { |i, hash| hash[keys[i]] = values[i] }
end

Instance Method Details

#aka(new_key, old_key) ⇒ Object



16
17
18
19
# File 'lib/lite/ruby/hash.rb', line 16

def aka(new_key, old_key)
  self[new_key] = self[old_key] if key?(old_key)
  self
end

#assert_all_min_keys!(*valid_keys) ⇒ Object

Raises:

  • (ArgumentError)


35
36
37
38
39
# File 'lib/lite/ruby/hash.rb', line 35

def assert_all_min_keys!(*valid_keys)
  return assert_min_keys!(*valid_keys) unless empty?

  raise ArgumentError, 'An empty hash is not allowed'
end

#assert_all_pair_presence!(*valid_keys) ⇒ Object

Raises:

  • (ArgumentError)


53
54
55
56
57
# File 'lib/lite/ruby/hash.rb', line 53

def assert_all_pair_presence!(*valid_keys)
  return assert_pair_presence!(*valid_keys) unless empty?

  raise ArgumentError, 'An empty hash is not allowed'
end

#assert_all_valid_keys!(*valid_keys) ⇒ Object

Raises:

  • (ArgumentError)


69
70
71
72
73
# File 'lib/lite/ruby/hash.rb', line 69

def assert_all_valid_keys!(*valid_keys)
  return assert_valid_keys!(*valid_keys) unless empty?

  raise ArgumentError, 'An empty hash is not allowed'
end

#assert_all_valid_values!(*valid_values) ⇒ Object

Raises:

  • (ArgumentError)


85
86
87
88
89
# File 'lib/lite/ruby/hash.rb', line 85

def assert_all_valid_values!(*valid_values)
  return assert_valid_values!(*valid_values) unless empty?

  raise ArgumentError, 'An empty hash is not allowed'
end

#assert_min_keys!(*valid_keys) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/lite/ruby/hash.rb', line 21

def assert_min_keys!(*valid_keys)
  return self if empty?

  valid_keys.each do |key|
    next if key?(key)

    raise ArgumentError,
          "Missing key: #{key.inspect}. " \
          "Minimum keys are: #{valid_keys.map(&:inspect).join(', ')}"
  end

  self
end

#assert_pair_presence!(*valid_keys) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/lite/ruby/hash.rb', line 41

def assert_pair_presence!(*valid_keys)
  each do |key, value|
    if !valid_keys.include?(key)
      raise ArgumentError,
            "Invalid key: #{key.inspect}. " \
            "Allowed keys are: #{valid_keys.map(&:inspect).join(', ')}"
    elsif value.respond_to?(:blank?) ? value.blank? : !value
      raise ArgumentError, "A #{value.inspect} value for #{key.inspect} is not allowed"
    end
  end
end

#assert_valid_keys!(*valid_keys) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/lite/ruby/hash.rb', line 59

def assert_valid_keys!(*valid_keys)
  each_key do |key|
    next if valid_keys.include?(key)

    raise ArgumentError,
          "Invalid key: #{key.inspect}. " \
          "Allowed keys are: #{valid_keys.map(&:inspect).join(', ')}"
  end
end

#assert_valid_values!(*valid_values) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/lite/ruby/hash.rb', line 75

def assert_valid_values!(*valid_values)
  each_value do |value|
    next if valid_values.include?(value)

    raise ArgumentError,
          "Invalid value: #{value.inspect}. " \
          "Allowed values are: #{valid_values.map(&:inspect).join(', ')}"
  end
end

#bury(*args) ⇒ Object

rubocop:disable Style/GuardClause



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/lite/ruby/hash.rb', line 92

def bury(*args)
  if args.count < 2
    raise ArgumentError, '2 or more arguments required'
  elsif args.count == 2
    self[args[0]] = args[1]
  else
    arg = args.shift
    self[arg] = {} unless self[arg]
    self[arg].bury(*args) unless args.empty?
  end

  self
end

#collate(*others) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/lite/ruby/hash.rb', line 108

def collate(*others)
  hash = {}

  each_key { |key| hash[key] = [] }

  others.each do |other|
    other.each_key { |key| hash[key] = [] }
  end

  each { |key, val| hash[key] << val }

  others.each do |other|
    other.each { |key, val| hash[key] << val }
  end

  hash.each_value(&:flatten!)
  hash
end

#collate!(other_hash) ⇒ Object

rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength



128
129
130
# File 'lib/lite/ruby/hash.rb', line 128

def collate!(other_hash)
  replace(collate(other_hash))
end

#collect_keys(&block) ⇒ Object Also known as: map_keys



132
133
134
# File 'lib/lite/ruby/hash.rb', line 132

def collect_keys(&block)
  keys.map(&block)
end

#collect_values(&block) ⇒ Object Also known as: map_values



136
137
138
# File 'lib/lite/ruby/hash.rb', line 136

def collect_values(&block)
  values.map(&block)
end

#dearray_singular_valuesObject



153
154
155
156
157
158
159
160
# File 'lib/lite/ruby/hash.rb', line 153

def dearray_singular_values
  each_with_object({}) do |(key, val), hash|
    hash[key] = case val
                when Array then val.size < 2 ? val[0] : val
                else val
                end
  end
end

#dearray_singular_values!Object



162
163
164
# File 'lib/lite/ruby/hash.rb', line 162

def dearray_singular_values!
  replace(dearray_singular_values)
end

#dearray_values(idx = 0) ⇒ Object



140
141
142
143
144
145
146
147
# File 'lib/lite/ruby/hash.rb', line 140

def dearray_values(idx = 0)
  each_with_object({}) do |(key, val), hash|
    hash[key] = case val
                when Array then val[idx] || val[-1]
                else val
                end
  end
end

#dearray_values!(idx = 0) ⇒ Object



149
150
151
# File 'lib/lite/ruby/hash.rb', line 149

def dearray_values!(idx = 0)
  replace(dearray_values(idx))
end

#deep_dupObject

rubocop:disable Style/CaseEquality



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/lite/ruby/safe/hash.rb', line 6

def deep_dup
  hash = dup

  each_pair do |key, value|
    if key.frozen? && ::String === key
      hash[key] = value.deep_dup
    else
      hash.delete(key)
      hash[key.deep_dup] = value.deep_dup
    end
  end

  hash
end

#deep_merge(other_hash, &block) ⇒ Object

rubocop:enable Style/CaseEquality



22
23
24
# File 'lib/lite/ruby/safe/hash.rb', line 22

def deep_merge(other_hash, &block)
  dup.deep_merge!(other_hash, &block)
end

#deep_merge!(other_hash, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/lite/ruby/safe/hash.rb', line 26

def deep_merge!(other_hash, &block)
  merge!(other_hash) do |key, this_val, other_val|
    if this_val.is_a?(Hash) && other_val.is_a?(Hash)
      this_val.deep_merge(other_val, &block)
    elsif defined?(yield)
      yield(key, this_val, other_val)
    else
      other_val
    end
  end
end

#delete_unlessObject



166
167
168
# File 'lib/lite/ruby/hash.rb', line 166

def delete_unless
  delete_if { |key, val| !yield(key, val) }
end

#delete_values(*values) ⇒ Object



170
171
172
173
174
175
176
177
# File 'lib/lite/ruby/hash.rb', line 170

def delete_values(*values)
  each_key.with_object([]) do |key, array|
    next unless values.include?(self[key])

    array << key
    delete(key)
  end
end

#demote(key) ⇒ Object



179
180
181
# File 'lib/lite/ruby/hash.rb', line 179

def demote(key)
  dup.demote!(key)
end

#demote!(key) ⇒ Object



183
184
185
186
187
188
# File 'lib/lite/ruby/hash.rb', line 183

def demote!(key)
  return self unless key?(key)

  self[key] = delete(key)
  self
end

#denillify(identity = 0) ⇒ Object



190
191
192
# File 'lib/lite/ruby/hash.rb', line 190

def denillify(identity = 0)
  dup.denillify!(identity)
end

#denillify!(identity = 0) ⇒ Object



194
195
196
# File 'lib/lite/ruby/hash.rb', line 194

def denillify!(identity = 0)
  each { |key, val| self[key] = val || identity }
end

#diff(hash) ⇒ Object



198
199
200
201
202
# File 'lib/lite/ruby/hash.rb', line 198

def diff(hash)
  h1 = dup.delete_if { |k, v| hash[k] == v }
  h2 = hash.dup.delete_if { |k, _| key?(k) }
  h1.merge(h2)
end

#except(*keys) ⇒ Object



38
39
40
# File 'lib/lite/ruby/safe/hash.rb', line 38

def except(*keys)
  slice(*self.keys - keys)
end

#except!(*keys) ⇒ Object



42
43
44
45
# File 'lib/lite/ruby/safe/hash.rb', line 42

def except!(*keys)
  keys.each { |key| delete(key) }
  self
end

#extract!(*keys) ⇒ Object



47
48
49
# File 'lib/lite/ruby/safe/hash.rb', line 47

def extract!(*keys)
  keys.each_with_object({}) { |key, hash| hash[key] = delete(key) if key?(key) }
end

#hmap(&block) ⇒ Object



204
205
206
# File 'lib/lite/ruby/hash.rb', line 204

def hmap(&block)
  dup.hmap!(&block)
end

#hmap!Object



208
209
210
# File 'lib/lite/ruby/hash.rb', line 208

def hmap!
  inject(self) { |hash, (key, val)| hash.merge(yield(key, val)) }
end

#insert(name, value) ⇒ Object



212
213
214
215
216
217
# File 'lib/lite/ruby/hash.rb', line 212

def insert(name, value)
  return false if key?(name)

  store(name, value)
  true
end

#invertObject



219
220
221
222
223
224
225
226
227
# File 'lib/lite/ruby/hash.rb', line 219

def invert
  each_pair.with_object({}) do |(key, val), hash|
    if val.is_a?(Array)
      val.each { |x| hash[x] = (hash.key?(x) ? [key, hash[x]].flatten : key) }
    else
      hash[val] = (hash.key?(val) ? [key, hash[val]].flatten : key)
    end
  end
end

#keys?(*check_keys) ⇒ Boolean Also known as: has_keys?

Returns:

  • (Boolean)


229
230
231
232
# File 'lib/lite/ruby/hash.rb', line 229

def keys?(*check_keys)
  unknown_keys = check_keys - keys
  unknown_keys.empty?
end

#nillifyObject



234
235
236
# File 'lib/lite/ruby/hash.rb', line 234

def nillify
  dup.nillify!
end

#nillify!Object



238
239
240
241
242
243
244
# File 'lib/lite/ruby/hash.rb', line 238

def nillify!
  each do |key, val|
    next if val.nil?

    self[key] = nil if respond_to?(:blank?) ? val.blank? : !val
  end
end

#only_fill(*keys, placeholder: nil) ⇒ Object



246
247
248
# File 'lib/lite/ruby/hash.rb', line 246

def only_fill(*keys, placeholder: nil)
  keys.each_with_object({}) { |key, hash| hash[key] = key?(key) ? self[key] : placeholder }
end

#only_fill!(*keys, placeholder: nil) ⇒ Object



250
251
252
# File 'lib/lite/ruby/hash.rb', line 250

def only_fill!(*keys, placeholder: nil)
  replace(only_fill(*keys, placeholder: placeholder))
end

#only_keys?(*check_keys) ⇒ Boolean Also known as: has_only_keys?

Returns:

  • (Boolean)


254
255
256
257
# File 'lib/lite/ruby/hash.rb', line 254

def only_keys?(*check_keys)
  unknown_keys = keys - check_keys
  unknown_keys.empty?
end

#pair?(key, value) ⇒ Boolean

Returns:

  • (Boolean)


259
260
261
# File 'lib/lite/ruby/hash.rb', line 259

def pair?(key, value)
  self[key] == value
end

#promote(key) ⇒ Object



263
264
265
# File 'lib/lite/ruby/hash.rb', line 263

def promote(key)
  dup.promote!(key)
end

#promote!(key) ⇒ Object



267
268
269
270
271
# File 'lib/lite/ruby/hash.rb', line 267

def promote!(key)
  return self unless key?(key)

  { key => delete(key) }.merge(self)
end

#rename_keys(*keys) ⇒ Object



273
274
275
# File 'lib/lite/ruby/hash.rb', line 273

def rename_keys(*keys)
  dup.rename_keys!(*keys)
end

#rename_keys!(*keys) ⇒ Object

rubocop:disable Style/HashConversion



278
279
280
281
# File 'lib/lite/ruby/hash.rb', line 278

def rename_keys!(*keys)
  keys = Hash[*keys]
  keys.each_with_object(self) { |(key, val), hash| hash[val] = delete(key) if hash[key] }
end

#reverse_merge(other_hash) ⇒ Object



51
52
53
# File 'lib/lite/ruby/safe/hash.rb', line 51

def reverse_merge(other_hash)
  other_hash.merge(self)
end

#reverse_merge!(other_hash) ⇒ Object



55
56
57
# File 'lib/lite/ruby/safe/hash.rb', line 55

def reverse_merge!(other_hash)
  other_hash.merge!(self)
end

#sampleObject

rubocop:enable Style/HashConversion



284
285
286
287
# File 'lib/lite/ruby/hash.rb', line 284

def sample
  key = sample_key
  [key, fetch(key)]
end

#sample!Object



289
290
291
292
293
# File 'lib/lite/ruby/hash.rb', line 289

def sample!
  key, value = sample
  delete(key)
  [key, value]
end

#sample_keyObject



295
296
297
298
# File 'lib/lite/ruby/hash.rb', line 295

def sample_key
  hash_keys = keys
  hash_keys.at(Random.rand(hash_keys.size - 1))
end

#sample_key!Object



300
301
302
303
304
# File 'lib/lite/ruby/hash.rb', line 300

def sample_key!
  key, _val = sample
  delete(key)
  key
end

#sample_valueObject



306
307
308
# File 'lib/lite/ruby/hash.rb', line 306

def sample_value
  fetch(sample_key)
end

#sample_value!Object



310
311
312
313
314
# File 'lib/lite/ruby/hash.rb', line 310

def sample_value!
  key, value = sample
  delete(key)
  value
end

#shuffleObject



316
317
318
# File 'lib/lite/ruby/hash.rb', line 316

def shuffle
  to_a.sample(size).to_h
end

#shuffle!Object



320
321
322
# File 'lib/lite/ruby/hash.rb', line 320

def shuffle!
  replace(shuffle)
end

#slice!(*keys) ⇒ Object Also known as: only!



324
325
326
327
328
329
330
331
# File 'lib/lite/ruby/hash.rb', line 324

def slice!(*keys)
  omit = slice(*self.keys - keys)
  hash = slice(*keys)
  hash.default = default
  hash.default_proc = default_proc if default_proc
  replace(hash)
  omit
end

#stringify_keysObject



59
60
61
# File 'lib/lite/ruby/safe/hash.rb', line 59

def stringify_keys
  transform_keys(&:to_s)
end

#stringify_keys!Object



63
64
65
# File 'lib/lite/ruby/safe/hash.rb', line 63

def stringify_keys!
  transform_keys!(&:to_s)
end

#stripObject



333
334
335
# File 'lib/lite/ruby/hash.rb', line 333

def strip
  reject { |_, val| respond_to?(:blank?) ? val.blank? : !val }
end

#strip!Object



337
338
339
# File 'lib/lite/ruby/hash.rb', line 337

def strip!
  reject! { |_, val| respond_to?(:blank?) ? val.blank? : !val }
end

#symbolize_and_underscore_keysObject

rubocop:disable Metrics/MethodLength



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/lite/ruby/hash.rb', line 342

def symbolize_and_underscore_keys
  each_with_object({}) do |(key, val), hash|
    new_key = begin
      str = key.dup.to_s
      str.gsub!(/::/, '/') || str
      str.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2') || str
      str.gsub!(/([a-z\d])([A-Z])/, '\1_\2') || str
      str.tr!(' -', '_') || str
      str.downcase!
      str.to_sym
    rescue StandardError
      key
    end

    hash[new_key] = val
  end
end

#symbolize_and_underscore_keys!Object

rubocop:enable Metrics/MethodLength



361
362
363
# File 'lib/lite/ruby/hash.rb', line 361

def symbolize_and_underscore_keys!
  replace(symbolize_and_underscore_keys)
end

#symbolize_keysObject



67
68
69
70
71
72
73
# File 'lib/lite/ruby/safe/hash.rb', line 67

def symbolize_keys
  transform_keys do |key|
    key.to_sym
  rescue StandardError
    key
  end
end

#symbolize_keys!Object



75
76
77
78
79
80
81
# File 'lib/lite/ruby/safe/hash.rb', line 75

def symbolize_keys!
  transform_keys! do |key|
    key.to_sym
  rescue StandardError
    key
  end
end

#to_objectObject Also known as: to_o



365
366
367
# File 'lib/lite/ruby/hash.rb', line 365

def to_object
  JSON.parse(to_json, object_class: OpenStruct)
end

#to_open_struct(lazy: true) ⇒ Object



369
370
371
372
373
# File 'lib/lite/ruby/hash.rb', line 369

def to_open_struct(lazy: true)
  struct = OpenStruct.new(self)
  struct.methods(lazy)
  struct
end

#to_structObject



375
376
377
378
# File 'lib/lite/ruby/hash.rb', line 375

def to_struct
  struct = Struct.new(*keys)
  struct.new(*values)
end

#update_eachObject



380
381
382
# File 'lib/lite/ruby/hash.rb', line 380

def update_each
  replace(each_with_object({}) { |(key, val), hash| hash.update(yield(key, val)) })
end

#update_keysObject



384
385
386
387
388
# File 'lib/lite/ruby/hash.rb', line 384

def update_keys
  return to_enum(:update_keys) unless defined?(yield)

  replace(each_with_object({}) { |(key, val), hash| hash[yield(key)] = val })
end

#update_valuesObject



390
391
392
393
394
# File 'lib/lite/ruby/hash.rb', line 390

def update_values
  return to_enum(:update_values) unless defined?(yield)

  replace(each_with_object({}) { |(key, val), hash| hash[key] = yield(val) })
end

#vacant?(key) ⇒ Boolean

Returns:

  • (Boolean)


396
397
398
399
# File 'lib/lite/ruby/hash.rb', line 396

def vacant?(key)
  value = self[key]
  respond_to?(:blank?) ? value.blank? : !value
end