Invokes the passed function for each key-value pair of this hash, passing the key and value to the function as the first two arguments. The method can take an optional second parameter as an Array object (arguments). The elements of this array will be passed to the function as additional parameters. Returns a new Hash consisting of entries for which the function returns True. Essentially the opposite of Hash.reject().

hash.keep(func as Function, arguments? as Array) as Hash


  • func. A reference to a function. This function must have been defined with at least two parameters as the current key and value will be passed to it. This function may have additional parameters defined and these will be passed to it as the contents of the optional arguments array
  • arguments. Optional Array object. Each element of this array will be passed to func as additional parameters after the current key and value


  • A new Hash object containing the key-value pairs for which the passed func function returned True


function even_key?(key, value) {
    return key % 2 == 0 ? True : False

var h = {1 => "first", 2 => "second", 3 => "third"}
var result = h.keep(even_key?)
print(h) # => {1 => "first", 2 => "second", 3 => "third"}
print(result) # => {2 => "second"}