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_valid_keys!(*valid_keys) ⇒ Object

Raises:

  • (ArgumentError)


29
30
31
32
33
# File 'lib/lite/ruby/hash.rb', line 29

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)


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

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_valid_keys!(*valid_keys) ⇒ Object



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

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



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

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



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/lite/ruby/hash.rb', line 52

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/MethodLength



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/lite/ruby/hash.rb', line 68

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/MethodLength



88
89
90
# File 'lib/lite/ruby/hash.rb', line 88

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

#collect_keysObject



92
93
94
# File 'lib/lite/ruby/hash.rb', line 92

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

#collect_valuesObject



96
97
98
# File 'lib/lite/ruby/hash.rb', line 96

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

#dearray_singular_valuesObject



113
114
115
116
117
118
119
120
# File 'lib/lite/ruby/hash.rb', line 113

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



122
123
124
# File 'lib/lite/ruby/hash.rb', line 122

def dearray_singular_values!
  replace(dearray_singular_values)
end

#dearray_values(idx = 0) ⇒ Object



100
101
102
103
104
105
106
107
# File 'lib/lite/ruby/hash.rb', line 100

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



109
110
111
# File 'lib/lite/ruby/hash.rb', line 109

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

#deep_dupObject

rubocop:disable Style/CaseEquality



127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/lite/ruby/hash.rb', line 127

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



143
144
145
# File 'lib/lite/ruby/hash.rb', line 143

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

#deep_merge!(other_hash, &block) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
# File 'lib/lite/ruby/hash.rb', line 147

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



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

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

#delete_values(*values) ⇒ Object



163
164
165
166
167
168
169
170
# File 'lib/lite/ruby/hash.rb', line 163

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



172
173
174
# File 'lib/lite/ruby/hash.rb', line 172

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

#demote!(key) ⇒ Object



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

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

  self[key] = delete(key)
  self
end

#denillify(identity = 0) ⇒ Object



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

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

#denillify!(identity = 0) ⇒ Object



187
188
189
# File 'lib/lite/ruby/hash.rb', line 187

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

#diff(hash) ⇒ Object



191
192
193
194
195
# File 'lib/lite/ruby/hash.rb', line 191

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



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

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

#except!(*keys) ⇒ Object



201
202
203
# File 'lib/lite/ruby/hash.rb', line 201

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

#extract!(*keys) ⇒ Object



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

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

#hmap(&block) ⇒ Object



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

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

#hmap!Object



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

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

#insert(name, value) ⇒ Object



217
218
219
220
221
222
# File 'lib/lite/ruby/hash.rb', line 217

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

  store(name, value)
  true
end

#invertObject



224
225
226
227
228
229
230
231
232
# File 'lib/lite/ruby/hash.rb', line 224

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)


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

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

#nillifyObject



241
242
243
# File 'lib/lite/ruby/hash.rb', line 241

def nillify
  dup.nillify!
end

#nillify!Object



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

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



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

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



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

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)


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

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

#pair?(key, value) ⇒ Boolean

Returns:

  • (Boolean)


266
267
268
# File 'lib/lite/ruby/hash.rb', line 266

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

#promote(key) ⇒ Object



270
271
272
# File 'lib/lite/ruby/hash.rb', line 270

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

#promote!(key) ⇒ Object



274
275
276
277
278
# File 'lib/lite/ruby/hash.rb', line 274

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

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

#rename_keys(*keys) ⇒ Object



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

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

#rename_keys!(*keys) ⇒ Object



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

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



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

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

#reverse_merge!(other_hash) ⇒ Object



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

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

#sampleObject



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

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

#sample!Object



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

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

#sample_keyObject



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

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

#sample_key!Object



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

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

#sample_valueObject



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

def sample_value
  fetch(sample_key)
end

#sample_value!Object



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

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

#shuffleObject



329
330
331
# File 'lib/lite/ruby/hash.rb', line 329

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

#shuffle!Object



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

def shuffle!
  replace(shuffle)
end

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



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

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



349
350
351
# File 'lib/lite/ruby/hash.rb', line 349

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

#stringify_keys!Object



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

def stringify_keys!
  replace(stringify_keys)
end

#stripObject



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

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

#strip!Object



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

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

#symbolize_and_underscore_keysObject

rubocop:disable Metrics/MethodLength



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/lite/ruby/hash.rb', line 382

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



401
402
403
# File 'lib/lite/ruby/hash.rb', line 401

def symbolize_and_underscore_keys!
  replace(symbolize_and_underscore_keys)
end

#symbolize_keysObject



365
366
367
368
369
370
371
372
373
374
375
# File 'lib/lite/ruby/hash.rb', line 365

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



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

def symbolize_keys!
  replace(symbolize_keys)
end

#to_objectObject Also known as: to_o



405
406
407
# File 'lib/lite/ruby/hash.rb', line 405

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

#update_eachObject



411
412
413
# File 'lib/lite/ruby/hash.rb', line 411

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

#update_keysObject



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

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



421
422
423
424
425
# File 'lib/lite/ruby/hash.rb', line 421

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)


427
428
429
# File 'lib/lite/ruby/hash.rb', line 427

def vacant?(key)
  self[key].blank?
end