从Ruby哈希中移动特定的匹配键值对

时间:2012-04-08 14:45:48

标签: ruby

我有一个Ruby哈希:

@tags = { "project_status" => { "title" => "Project status" }, 
          "milestones"     => { "title" => "Milestones"},
          "lessons"        => { "title" => "Lessons"}, 
          "tasks"          => { "title" => "Tasks"} }

我想从此哈希中shift特定的键值对。 例如如果我对"milestones"标记感兴趣,那么哈希上的shift会给我:

=> ["milestones", {"title"=>"Milestones"}] 

这正是我想要的。

除外,我无法弄清楚如何选择特定的键值对。

我可以编写一些东西来遍历哈希,直到我找到匹配的密钥,然后调用shift,但我假设有一个更干净的“Ruby方式”来执行此操作:)

1 个答案:

答案 0 :(得分:4)

delete可能就是你要找的东西。它从散列中删除相应的键(而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"}}