rails/rails — pull request #15272 by DNNX (2014-05-23 15:04:15+00:00)
Title: Replace a loop with `Hash#slice`

Because it is shorter and works faster.
Here are some benchmarks.

```ruby
require 'benchmark'

def test
1_000_000.times do
h = { a: 1, b: 2, c: 3}
keys_to_keep = [:b, :c, :d]
h = yield h, keys_to_keep
end
end

def test_slice!
test do |h, keys_to_keep|
h.slice!(*keys_to_keep)
h
end
end

def test_slice
test do |h, keys_to_keep|
h = h.slice(*keys_to_keep)
h
end
end

def test_delete
test do |h, keys_to_keep|
(h.keys - keys_to_keep).each do |bad_key|
h.delete(bad_key)
end
h
end
end

Benchmark.bmbm(9) do |x|
x.report("slice!") { test_slice! }
x.report("slice") { test_slice }
x.report("delete") { test_delete }
end

__END__
Rehearsal ---------------------------------------------
slice! 19.250000 0.070000 19.320000 ( 19.504436)
slice 6.890000 0.040000 6.930000 ( 6.953150)
delete 9.780000 0.030000 9.810000 ( 9.887094)
----------------------------------- total: 36.060000sec

user system total real
slice! 19.220000 0.060000 19.280000 ( 19.341210)
slice 6.720000 0.040000 6.760000 ( 6.771572)
delete 9.590000 0.030000 9.620000 ( 9.654327)
```