Method: Cod::SelectGroup#keep_if

Defined in:
lib/cod/select_group.rb

#keep_if(&block) ⇒ Object

Keeps values around with their respective keys if block returns true for the values. Deletes everything else. NOT like Hash#keep_if.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cod/select_group.rb', line 40

def keep_if(&block)
  old_hash = @h
  @h = Hash.new
  old_hash.each do |key, values|
    # Now values is either an Array like structure that we iterate 
    # on or it is a single value. 
    if values.respond_to?(:to_ary)
      ary = values.select { |e| block.call(e) }
      @h[key] = ary unless ary.empty?
    else
      value = values
      @h[key] = value if block.call(value)
    end
  end
  
  self
end