我有一个带有几百个值的哈希值,其中一些值是:
plays = {"week 1" => 0, "week 2" => 0, etc}
我想删除其密钥中包含单词"week"
的任何键/值对。我似乎无法用plays.delete
做到这一点。这样做的最佳方式是什么?
答案 0 :(得分:3)
答案 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,在这种情况下,最好避免使用正则表达式。)