繁体   English   中英

从 Ruby 到 hash 移动特定的匹配键值对

[英]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.

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