Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/casual_support/hash/putbang.rb,
lib/casual_support/hash/displace.rb

Instance Method Summary collapse

Instance Method Details

#displace(key, value) ⇒ Hash

Associates a key with a value, and returns the key’s previously associated value. If the key had no previously associated value, returns Hash#default.

Examples:

visited = { "id1" => true, "id2" => false }

visited.displace("id1", true)  # == true
visited                        # == { "id1" => true, "id2" => false }
visited.displace("id2", true)  # == false
visited                        # == { "id1" => true, "id2" => true }
visited.displace("id3", true)  # == nil
visited                        # == { "id1" => true, "id2" => true, "id3" => true }

Parameters:

  • key
  • value

Returns:



20
21
22
23
24
# File 'lib/casual_support/hash/displace.rb', line 20

def displace(key, value)
  old_value = self[key]
  self[key] = value
  old_value
end

#put!(key, value) ⇒ Hash

Associates a key with a value. Similar to Hash#[]=, but returns the Hash instead of the value. Faster than Hash#merge! for singular values in a loop.

Examples:

cache = id_list.reduce({}) do |hash, id|
  hash.put!(id, find_by_id(id))
end

Parameters:

  • key
  • value

Returns:



15
16
17
18
# File 'lib/casual_support/hash/putbang.rb', line 15

def put!(key, value)
  self[key] = value
  self
end