user3467349
user3467349

Reputation: 3191

Ruby pop an element from a hash table?

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

Upvotes: 10

Views: 8156

Answers (1)

Björn Nilsson
Björn Nilsson

Reputation: 3773

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.

Upvotes: 16

Related Questions