简体   繁体   中英

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.

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

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

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM