Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby pop an element from a hash table?

Tags:

ruby

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
like image 572
user3467349 Avatar asked May 15 '15 02:05

user3467349


People also ask

How do I get the hash value in Ruby?

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.

How do you pop in Ruby?

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.

How does .POP work in Ruby?

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.


1 Answers

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.

like image 197
Björn Nilsson Avatar answered Nov 07 '22 23:11

Björn Nilsson