Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/tap/formatters/core_ext/hash.rb

Overview

Extensions to the core String class

Instance Method Summary collapse

Instance Method Details

#compact ⇒ Hash

Removes nil and blank values. The value is either +NilClass+ or +String+.

Examples:

{ you: 0, me: nil, we: '  ' }.compact
#=> { you: 0 }

Returns:

  • (Hash) —

    compact hash



14
15
16
# File 'lib/rspec/tap/formatters/core_ext/hash.rb', line 14

def compact
  reject { |_, value| value.nil? || value.blank? }
end

#stringify_keys ⇒ Hash

Transforms hash keys by using +to_s+. The value is either +NilClass+ or +String+.

Examples:

{ you: 0, me: nil, we: '  '}.stringify_keys
#=> { "you" => 0, "me" => nil, "we" => '  '}

Returns:

  • (Hash) —

    with transformed keys



48
49
50
# File 'lib/rspec/tap/formatters/core_ext/hash.rb', line 48

def stringify_keys
  transform_keys(&:to_s)
end

#transform_keys ⇒ Hash

Transforms hash keys. The value is either +NilClass+ or +String+.

Examples:

{ you: 0, me: nil, we: '  '}.transform_keys(&:upcase)
#=> { YOU: 0, ME: nil, WE: '  '}

Returns:

  • (Hash) —

    with transformed keys



28
29
30
31
32
33
34
35
36
# File 'lib/rspec/tap/formatters/core_ext/hash.rb', line 28

def transform_keys
  return enum_for(:transform_keys) { size } unless block_given?

  new_hash = {}

  each_key { |key| new_hash[yield(key)] = self[key] }

  new_hash
end