Module: HashUtils

Defined in:
lib/buzzcore/extend_base_classes.rb

Instance Method Summary collapse

Instance Method Details

#filter_exclude(aKeys, aHash = nil) ⇒ Object



330
331
332
333
# File 'lib/buzzcore/extend_base_classes.rb', line 330

def filter_exclude(aKeys,aHash=nil)
  aHash ||= self
  filter_exclude!(aKeys,aHash.clone)
end

#filter_exclude!(aKeys, aHash = nil) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
# File 'lib/buzzcore/extend_base_classes.rb', line 318

def filter_exclude!(aKeys,aHash=nil)
  aHash ||= self

  if aKeys.is_a? Regexp
    return aHash.delete_if {|k,v| k =~ aKeys }
  else
    aKeys = [aKeys] unless aKeys.is_a? Array
    return aHash if aKeys.empty?
    return aHash.delete_if {|key, value| ((aKeys.include?(key)) || (key.is_a?(Symbol) and aKeys.include?(key.to_s)) || (key.is_a?(String) and aKeys.include?(key.to_sym)))}
  end
end

#filter_include(aKeys, aHash = nil) ⇒ Object



313
314
315
316
# File 'lib/buzzcore/extend_base_classes.rb', line 313

def filter_include(aKeys,aHash=nil)
  aHash ||= self
  filter_include!(aKeys,aHash.clone)
end

#filter_include!(aKeys, aHash = nil) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/buzzcore/extend_base_classes.rb', line 300

def filter_include!(aKeys,aHash=nil)
  aHash ||= self

  if aKeys.is_a? Regexp
    return aHash.delete_if {|k,v| not k =~ aKeys }
  else
    aKeys = [aKeys] unless aKeys.is_a? Array
    return aHash.clear if aKeys.empty?
    return aHash.delete_if {|key, value| !((aKeys.include?(key)) || (key.is_a?(Symbol) and aKeys.include?(key.to_s)) || (key.is_a?(String) and aKeys.include?(key.to_sym)))}
    return aHash  # last resort
  end
end

#has_values_for?(aKeys, aHash = nil) ⇒ Boolean

Returns:

  • (Boolean)


335
336
337
338
339
# File 'lib/buzzcore/extend_base_classes.rb', line 335

def has_values_for?(aKeys,aHash=nil)
  aHash ||= self
  # check all keys exist in aHash and their values are not nil
  aKeys.all? { |k,v| aHash[k] }
end

#symbolize_keysObject



361
362
363
364
365
# File 'lib/buzzcore/extend_base_classes.rb', line 361

def symbolize_keys
  result = {}
  self.each { |k,v| k.is_a?(String) ? result[k.to_sym] = v : result[k] = v  }
  return result
end

#to_nilObject



367
368
369
# File 'lib/buzzcore/extend_base_classes.rb', line 367

def to_nil
  self.empty? ? nil : self
end

#without_key(aKey) ⇒ Object

give a block to execute without the given key in this hash It will be replaced after the block (guaranteed by ensure) eg. hash.without_key(:blah) do |aHash| puts aHash.inspect end



347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/buzzcore/extend_base_classes.rb', line 347

def without_key(aKey)
  temp = nil
  h = self
  begin
    if h.include?(aKey)
      temp = [aKey,h.delete(aKey)]
    end
    result = yield(h)
  ensure
    h[temp[0]] = temp[1] if temp
  end
  return result
end