Instance Methods Flashcards
clear
Fn: Removes all key-value pairs from the hash
Returns: original hash
Syntax: my_hash.clear
invert
Fn: switch around the keys with the values
Returns: new hash
Syntax: my_hash.invert
#keys #values
Fn: create a new array with the keys/values of the hash as elements
Returns: a new array
Syntax: my_hash.keys(values)
values_at
Fn: returns the values associated with the given keys
Returns: an array of the values
Syntax: my_hash.values_at(key…)
update
Fn: Add the contents of another hash (overwriting with values from the new hash unless a block is specified)
Returns: original hash
Syntax: my_hash.update(new_hash)
#merge #merge!
Fn: Returns a hash containing values from both
Returns: a new hash/original hash (!)
Syntax: same as #update
has_key? / #key? / #member
Fn: returns true if the given key is present in hash
Returns: Boolean
Syntax: my_hash.hash_key(key)
has_value? / #value?
Fn: returns true if the hash contains the given value
Returns: Boolean
Syntax: same as #key?
#each_key #each_value
Fn: Calls the block once for each key, passing the key/value as a parameter
Returns: original hash
Syntax: my_hash.each_key{|key| block}
my_hash.each_value{|value| block}
each_pair
Fn: Calls the block once for each key in the hash, passing both key and value as parameters.
Returns: original hash
Syntax: my_hash.each_pair{|key, value| block}
eql?
Fn: returns true if both arguments are hashes with the same content
Returns: Boolean
Syntax: my_hash.eql?(other_hash)
to_s
Returns a string representation of the hash
length
Returns the number of key-value pairs in the hash
#delete_if #keep_if
Like the array versions, only there are parameters in the block for both key and value rather than just index.
Destructive.
flatten
Fn: Returns an array that is a one-dimensional flattening of the hash. Does not flatten recursively, just to the given level.
Returns: an array
Syntax: my_hash.flatten(level)