Class: Hash

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.zip(keys, values) ⇒ Object



8
9
10
# File 'lib/lite/ruby/hash.rb', line 8

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



14
15
16
17
# File 'lib/lite/ruby/hash.rb', line 14

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)


33
34
35
36
37
# File 'lib/lite/ruby/hash.rb', line 33

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)


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

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)


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

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)


83
84
85
86
87
# File 'lib/lite/ruby/hash.rb', line 83

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



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

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



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

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



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

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



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

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



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

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/CyclomaticComplexity, Metrics/MethodLength



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

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/CyclomaticComplexity, Metrics/MethodLength



126
127
128
# File 'lib/lite/ruby/hash.rb', line 126

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

#collect_keysObject



130
131
132
# File 'lib/lite/ruby/hash.rb', line 130

def collect_keys
  collect { |key, _| yield(key) }
end

#collect_valuesObject



134
135
136
# File 'lib/lite/ruby/hash.rb', line 134

def collect_values
  collect { |_, val| yield(val) }
end

#dearray_singular_valuesObject



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

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



160
161
162
# File 'lib/lite/ruby/hash.rb', line 160

def dearray_singular_values!
  replace(dearray_singular_values)
end

#dearray_values(idx = 0) ⇒ Object



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

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



147
148
149
# File 'lib/lite/ruby/hash.rb', line 147

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

#deep_dupObject

rubocop:disable Style/CaseEquality



165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/lite/ruby/hash.rb', line 165

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



181
182
183
# File 'lib/lite/ruby/hash.rb', line 181

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

#deep_merge!(other_hash, &block) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/lite/ruby/hash.rb', line 185

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 block_given?
      yield(key, this_val, other_val)
    else
      other_val
    end
  end
end

#delete_unlessObject



197
198
199
# File 'lib/lite/ruby/hash.rb', line 197

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

#delete_values(*values) ⇒ Object



201
202
203
204
205
206
207
208
# File 'lib/lite/ruby/hash.rb', line 201

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



210
211
212
# File 'lib/lite/ruby/hash.rb', line 210

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

#demote!(key) ⇒ Object



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

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

  self[key] = delete(key)
  self
end

#denillify(identity = 0) ⇒ Object



221
222
223
# File 'lib/lite/ruby/hash.rb', line 221

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

#denillify!(identity = 0) ⇒ Object



225
226
227
# File 'lib/lite/ruby/hash.rb', line 225

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

#diff(hash) ⇒ Object



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

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



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

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

#except!(*keys) ⇒ Object



239
240
241
# File 'lib/lite/ruby/hash.rb', line 239

def except!(*keys)
  keys.each_with_object(self) { |key, _| delete(key) }
end

#extract!(*keys) ⇒ Object



243
244
245
# File 'lib/lite/ruby/hash.rb', line 243

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

#hmap(&block) ⇒ Object



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

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

#hmap!Object



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

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

#insert(name, value) ⇒ Object



255
256
257
258
259
260
# File 'lib/lite/ruby/hash.rb', line 255

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

  store(name, value)
  true
end

#invertObject



262
263
264
265
266
267
268
269
270
# File 'lib/lite/ruby/hash.rb', line 262

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)


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

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

#nillifyObject



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

def nillify
  dup.nillify!
end

#nillify!Object



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

def nillify!
  each do |key, val|
    self[key] = nil if !val.nil? && (val.try(:blank?) || val.try(:to_s).blank?)
  end
end

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



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

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



293
294
295
# File 'lib/lite/ruby/hash.rb', line 293

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)


297
298
299
300
# File 'lib/lite/ruby/hash.rb', line 297

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

#pair?(key, value) ⇒ Boolean

Returns:

  • (Boolean)


304
305
306
# File 'lib/lite/ruby/hash.rb', line 304

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

#promote(key) ⇒ Object



308
309
310
# File 'lib/lite/ruby/hash.rb', line 308

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

#promote!(key) ⇒ Object



312
313
314
315
316
# File 'lib/lite/ruby/hash.rb', line 312

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

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

#rename_keys(*keys) ⇒ Object



318
319
320
# File 'lib/lite/ruby/hash.rb', line 318

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

#rename_keys!(*keys) ⇒ Object



322
323
324
325
# File 'lib/lite/ruby/hash.rb', line 322

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



327
328
329
# File 'lib/lite/ruby/hash.rb', line 327

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

#reverse_merge!(other_hash) ⇒ Object



331
332
333
# File 'lib/lite/ruby/hash.rb', line 331

def reverse_merge!(other_hash)
  replace(reverse_merge(other_hash))
end

#sampleObject



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

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

#sample!Object



340
341
342
343
344
# File 'lib/lite/ruby/hash.rb', line 340

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

#sample_keyObject



346
347
348
349
# File 'lib/lite/ruby/hash.rb', line 346

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

#sample_key!Object



351
352
353
354
355
# File 'lib/lite/ruby/hash.rb', line 351

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

#sample_valueObject



357
358
359
# File 'lib/lite/ruby/hash.rb', line 357

def sample_value
  fetch(sample_key)
end

#sample_value!Object



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

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

#shuffleObject



367
368
369
# File 'lib/lite/ruby/hash.rb', line 367

def shuffle
  Hash[to_a.sample(size)]
end

#shuffle!Object



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

def shuffle!
  replace(shuffle)
end

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



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

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



387
388
389
# File 'lib/lite/ruby/hash.rb', line 387

def stringify_keys
  each_with_object({}) { |(key, val), hash| hash[key.to_s] = val }
end

#stringify_keys!Object



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

def stringify_keys!
  replace(stringify_keys)
end

#stripObject



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

def strip
  select { |_, val| !val.blank? }
end

#strip!Object



399
400
401
# File 'lib/lite/ruby/hash.rb', line 399

def strip!
  reject! { |_, val| val.blank? }
end

#symbolize_and_underscore_keysObject

rubocop:disable Metrics/MethodLength



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/lite/ruby/hash.rb', line 420

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

    hash[new_key] = val
  end
end

#symbolize_and_underscore_keys!Object

rubocop:enable Metrics/MethodLength



439
440
441
# File 'lib/lite/ruby/hash.rb', line 439

def symbolize_and_underscore_keys!
  replace(symbolize_and_underscore_keys)
end

#symbolize_keysObject



403
404
405
406
407
408
409
410
411
412
413
# File 'lib/lite/ruby/hash.rb', line 403

def symbolize_keys
  each_with_object({}) do |(key, val), hash|
    new_key = begin
                key.to_s.to_sym
              rescue StandardError
                key
              end

    hash[new_key] = val
  end
end

#symbolize_keys!Object



415
416
417
# File 'lib/lite/ruby/hash.rb', line 415

def symbolize_keys!
  replace(symbolize_keys)
end

#to_objectObject Also known as: to_o



443
444
445
# File 'lib/lite/ruby/hash.rb', line 443

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

#to_open_struct(lazy: true) ⇒ Object



449
450
451
452
453
# File 'lib/lite/ruby/hash.rb', line 449

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

#to_structObject



455
456
457
458
# File 'lib/lite/ruby/hash.rb', line 455

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

#update_eachObject



460
461
462
# File 'lib/lite/ruby/hash.rb', line 460

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

#update_keysObject



464
465
466
467
468
# File 'lib/lite/ruby/hash.rb', line 464

def update_keys
  return to_enum(:update_keys) unless block_given?

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

#update_valuesObject



470
471
472
473
474
# File 'lib/lite/ruby/hash.rb', line 470

def update_values
  return to_enum(:update_values) unless block_given?

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

#vacant?(key) ⇒ Boolean

Returns:

  • (Boolean)


476
477
478
479
# File 'lib/lite/ruby/hash.rb', line 476

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