Some_hash.delete_if {|key, value| key == "at" || key == "with" || key == "from"}
我刚刚包括3个但我有一个7的列表,这条线变得很长很丑。有没有办法以更短的方式做到这一点,而不必每次都做key == SOMEVALUE
?Ruby hash delete_if许多
Some_hash.delete_if {|key, value| key == "at" || key == "with" || key == "from"}
我刚刚包括3个但我有一个7的列表,这条线变得很长很丑。有没有办法以更短的方式做到这一点,而不必每次都做key == SOMEVALUE
?Ruby hash delete_if许多
请注意'#except'返回一个重复的散列,其中的键已被删除,请参阅'#except!'以获取就地增量。 – user2864740
%w[at with from]
.each_with_object(Some_hash){|k, h| h.delete(k)}
尝试:
keys_to_remove = ['at', 'with', 'from']
hash.delete_if {|key,_| keys_to_remove.include? key}
结束了这个虽然@冰人的答案是最好的! –
http://stackoverflow.com/questions/16574162/simplifying-a-check-in-ruby – user2864740
这个答案不使用Rails中包含的方便的方法。 – Iceman
@Iceman好点。我已投票重新开放。 – user2864740