2014-05-21 43 views
1
Some_hash.delete_if {|key, value| key == "at" || key == "with" || key == "from"} 

我刚刚包括3个但我有一个7的列表,这条线变得很长很丑。有没有办法以更短的方式做到这一点,而不必每次都做key == SOMEVALUERuby hash delete_if许多

+0

http://stackoverflow.com/questions/16574162/simplifying-a-check-in-ruby – user2864740

+0

这个答案不使用Rails中包含的方便的方法。 – Iceman

+0

@Iceman好点。我已投票重新开放。 – user2864740

回答

6
SomeHash.except(:key1, :key2, ...) 

Rails有得心应手Hash#except扩展:

返回包含一切,但给定的密钥的哈希值。

+4

请注意'#except'返回一个重复的散列,其中的键已被删除,请参阅'#except!'以获取就地增量。 – user2864740

3
%w[at with from] 
.each_with_object(Some_hash){|k, h| h.delete(k)} 
3

尝试:

keys_to_remove = ['at', 'with', 'from'] 
hash.delete_if {|key,_| keys_to_remove.include? key} 
+0

结束了这个虽然@冰人的答案是最好的! –