labyrinth
labyrinth

Reputation: 13946

Is there an equivalent pop method in Ruby for hashes similar to Python dictionaries?

In Python you can do something like:

d = {"Austria": "Vienna", "Peru": "Lima"}
d.pop("Austria")

"Vienna" is returned, and the "Austria":"Vienna" pair is deleted from d.

Is there something analogous in Ruby? I think I know the answer but I haven't seen this asked yet on SO and want to confirm I'm correct.

Upvotes: 0

Views: 449

Answers (2)

Nick Veys
Nick Veys

Reputation: 23939

Yup, delete.

[1] pry(main)> d = { "Austria" => "Vienna", "Peru" => "Lima" }
=> {"Austria"=>"Vienna", "Peru"=>"Lima"}
[2] pry(main)> d.delete('Austria')
=> "Vienna"
[3] pry(main)> d
=> {"Peru"=>"Lima"}

Upvotes: 2

falsetru
falsetru

Reputation: 369154

Hash#delete is similar to dict.pop in Python.

h = {"Austria" => "Vienna", "Peru" => "Lima"}
h.delete("Austria")
# => "Vienna"
h
# => {"Peru"=>"Lima"}

Upvotes: 2

Related Questions