Removing Select Elements From a Ruby Array With Keep_if

Array#keep_if has been in Ruby since 1.9.2 and works much like Array#select but in reverse. The main difference is that elements in the array are removed if the block evaluates false. It’s a useful array method to use when you want to empty your array, except for values that match some condition.

1
2
3
arr = ["thing","thang","thong"]
arr.keep_if{|v| v != "thing"} #=> ["thang", "thong"]
arr.keep_if{|v| v == "thang"} #=> ["thang"]

Array#keep_if is essentially an alias for Array#select!, the bang method cousin of Array#select, but with a much more intuitive method name. Array#select! is a destructive method so the bang is appropriate but it’s a misleading method name for sure.