Class: SliceableHash

Inherits:
Object
  • Object
show all
Defined in:
lib/ext/sliceable_hash.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ SliceableHash

Returns a new instance of SliceableHash.



3
4
5
# File 'lib/ext/sliceable_hash.rb', line 3

def initialize(hash)
  @hash = hash
end

Instance Method Details

#if_string_not_empty(val) ⇒ Object



13
14
15
# File 'lib/ext/sliceable_hash.rb', line 13

def if_string_not_empty(val)
  val.kind_of?(String) ? !val.empty? : true
end

#slice(*keys) ⇒ Object

Return a hash that includes only the given keys.



8
9
10
11
# File 'lib/ext/sliceable_hash.rb', line 8

def slice(*keys)
  keys.map! { |key| @hash.convert_key(key) } if @hash.respond_to?(:convert_key, true)
  keys.each_with_object(@hash.class.new) { |k, hash| hash[k] = @hash[k] if @hash.has_key?(k) && if_string_not_empty(@hash[k]) }
end