Find all : Hash Extensions « Hash « Ruby






Find all


class Hash
  def find_all
    new_hash = Hash.new
    each { |k,v| new_hash[k] = v if yield(k, v) }
    new_hash
  end
end

squares = {0=>0, 1=>1, 2=>4, 3=>9}
squares.find_all { |key, value| key > 1 }        # => {2=>4, 3=>9}

 








Related examples in the same category

1.Add method to Hash class to remove one hash from another
2.Add method hash class to invert a hash: turn value to key
3.Grep a hash