Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Hash#delete

(::Hash::_Key key) -> V?
[T, K2 < ::Hash::_Key] (K2 key) { (K2 key) -> T } -> (T | V)
delete(key) → value or nil
delete(key) {|key| ... } → object

If an entry for the given key is found, deletes the entry and returns its associated value; otherwise returns nil or calls the given block.

With no block given and key found, deletes the entry and returns its value:

Example
h = {foo: 0, bar: 1, baz: 2}
h.delete(:bar) # => 1
h # => {foo: 0, baz: 2}

With no block given and key not found, returns nil.

With a block given and key found, ignores the block, deletes the entry, and returns its value:

Example
h = {foo: 0, bar: 1, baz: 2}
h.delete(:baz) { |key| raise 'Will never happen'} # => 2
h # => {foo: 0, bar: 1}

With a block given and key not found, calls the block and returns the block’s return value:

Example
h = {foo: 0, bar: 1, baz: 2}
h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
h # => {foo: 0, bar: 1, baz: 2}

Related: see Methods for Deleting.

See also #default_proc= #delete_if #default_proc #dig also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0