tl;dr: delete_if
seems slightly faster. However, the main consideration for choosing a method is the difference in the return value, as pointed out in the other answers.
Since you clarified that your question is concerning efficiency, I did a few tests:
> time { (1..100000).to_a.reject!{ |n| n % 5 == 0 } }
0.390000 0.000000 0.390000 ( 0.394596)
> time { (1..100000).to_a.delete_if{ |n| n % 5 == 0 } }
0.400000 0.000000 0.400000 ( 0.399122)
> time { (1..200000).to_a.reject!{ |n| n % 5 == 0 } }
1.650000 0.000000 1.650000 ( 1.657927)
> time { (1..200000).to_a.delete_if{ |n| n % 5 == 0 } }
1.630000 0.010000 1.640000 ( 1.637719)
> time { (1..300000).to_a.reject!{ |n| n % 5 == 0 } }
3.700000 0.000000 3.700000 ( 3.717206)
> time { (1..300000).to_a.delete_if{ |n| n % 5 == 0 } }
3.660000 0.000000 3.660000 ( 3.686213)
> time { (1..400000).to_a.reject!{ |n| n % 5 == 0 } }
7.320000 0.020000 7.340000 ( 7.361767)
> time { (1..400000).to_a.delete_if{ |n| n % 5 == 0 } }
7.190000 0.020000 7.210000 ( 7.239549)
So, looks like that beyond a certain size delete_if
is slightly faster.
time
is defined as:
def time(&block)
puts Benchmark.measure(&block)
end
The numbers represent user CPU time, system CPU time, the sum of the user and system CPU times, and the elapsed real time, respectively. You can find here an explanation of their meanings.
Note that as in every benchmark, YMMV, and you should test on your specific workflows rather than my contrived example of removing numbers that are multiples of 5.