method

delete

Importance_2
Ruby latest stable (v1_8_7_72) - 2 notes - Class: Hash
delete(p1) public

Deletes and returns a key-value pair from hsh whose key is equal to key. If the key is not found, returns nil. If the optional code block is given and the key is not found, pass in the key and return the result of block.

   h = { "a" => 100, "b" => 200 }
   h.delete("a")                              #=> 100
   h.delete("z")                              #=> nil
   h.delete("z") { |el| "#{el} not found" }   #=> "z not found"
Show source
Register or log in to add new notes.
October 7, 2009
1 thank

Hash#without

Here’s a small helper for doing the "opposite" of this method:

  class Hash
    def without(*keys)
      cpy = self.dup
      keys.each { |key| cpy.delete(key) }
      cpy
    end
  end

  h = { :a => 1, :b => 2, :c => 3 }
  h.without(:a)      #=> { :b => 2, :c => 3 }
  h.without(:a, :c)  #=> { :b => 2 }
February 19, 2010
1 thank

Hash#except

Note that the ActiveSupport library provides the except and except! methods, which return the Hash minus the given keys. So you don’t need to write your own wrapper if you happen to be using Rails or ActiveSupport as a stand-alone library:

http://apidock.com/rails/ActiveSupport/CoreExtensions/Hash/Except/except