[英]Shifting a specific matching key-value pair from Ruby hash
我有一個 Ruby hash:
@tags = { "project_status" => { "title" => "Project status" },
"milestones" => { "title" => "Milestones"},
"lessons" => { "title" => "Lessons"},
"tasks" => { "title" => "Tasks"} }
我想shift
這個 hash 中移出特定的鍵值對。例如,如果我對"milestones"
標簽感興趣,那么shift
hash 上會給我:
=> ["milestones", {"title"=>"Milestones"}]
這正是我想要的。
除了我不知道如何 select 一個特定的鍵值對。
我可以寫一些東西來遍歷 hash 直到我找到匹配的鍵然后調用shift
,但我假設有一個更干凈的“Ruby 方式”來做到這一點:)
delete
可能是你要找的。 它從 hash 中刪除相應的鍵(而shift
從數組中刪除項目)
tags = { "project_status" => { "title" => "Project status" },
"milestones" => { "title" => "Milestones"},
"lessons" => { "title" => "Lessons"},
"tasks" => { "title" => "Tasks"} }
def shift hash, key
[key, hash.delete(key)] # removes key/value pair
# [key, hash[key]] # leaves key/value pair
end
shift tags, 'milestones' # => ["milestones", {"title"=>"Milestones"}]
tags # => {"project_status"=>{"title"=>"Project status"}, "lessons"=>{"title"=>"Lessons"}, "tasks"=>{"title"=>"Tasks"}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.