1

我有一个 Ruby 哈希:

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

我想shift从这个哈希中取出特定的键值对。例如,如果我对"milestones"标签感兴趣,那么shift在哈希上会给我:

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

这正是我想要的。

除了我不知道如何选择特定的键值对。

我可以写一些东西来遍历哈希,直到找到匹配的键然后调用shift,但我假设有一个更干净的“Ruby方式”来做到这一点:)

4

1 回答 1

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"}}
于 2012-04-08T14:57:48.547 回答