通过匹配字符从哈希中删除键

时间:2015-01-31 11:33:20

标签: ruby hash

我有一个带有几百个值的哈希值,其中一些值是:

plays = {"week 1" => 0, "week 2" => 0, etc}

我想删除其密钥中包含单词"week"的任何键/值对。我似乎无法用plays.delete做到这一点。这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:3)

您可以使用Hash#delete_if

play.delete_if { |k,_| /week/ ===  k }

我使用了这种方法:Regexp#===

答案 1 :(得分:2)

让:

plays = { "week 1" => 0, "week 2" => 0, "dog" => "woof" } 

如果您不想损坏plays,请使用Hash#reject

plays.reject { |k,v| k.include?('week') }
  #=> "woof"

plays
  #=> {"week 1"=>0, "week 2"=>0, "dog"=>"woof"} 

(我最初有k =~ /week/。我同意@sawa,在这种情况下,最好避免使用正则表达式。)