I am looking at http://ruby-doc.org/core-1.9.3/Hash.html and there does not appear to be a pop
method? I think I am missing something though...
if (x = d['a']) != nil
d.delete('a')
end
In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.
Ruby | pop() functionThe pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements. Parameters: Elements : This is the number of elements which are to be removed from the end of the given array.
pop() in Ruby? pop() is a Ruby array method that pops or removes the last element of a given array. It permanently removes the last element of an array.
If you know the key, just use delete directly if the hash doesn't contain the key, you will get nil back, otherwise you will get whatever was stored there
from the doc you linked to:
h = { "a" => 100, "b" => 200 }
h.delete("a") #=> 100
h.delete("z") #=> nil
h.delete("z") { |el| "#{el} not found" } #=> "z not found"
There is also shift which deletes and returns a key-value pair:
hsh = Hash.new
hsh['bb'] = 42
hsh['aa'] = 23
hsh['cc'] = 65
p hsh.shift
=> ["bb", 42]
As can be seen, the order of a hash is the order of insertion, not the key or value. From the doc
Hashes enumerate their values in the order that the corresponding keys were inserted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With