Project

General

Profile

Actions

Feature #10270

closed

Hash#insert

Added by atlas (Atlas Prime) over 9 years ago. Updated over 9 years ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-core:65171]

Description

Hash doesn't appear to have a "safe" way to insert an entry that won't clobber another key if it is already there. So how about:

class Hash

  # Like Hash#store but only stores if the key isn't already
  # in the hash. Returns true if inserted, otherwise false.
  #
  def insert(name, value)
    if key?(name)
      false
    else
      store(name,value)
      true
    end
  end

end
Actions

Also available in: Atom PDF

Like0
Like0Like0