I'm new to ruby and was going though a piece of code
scope_value = {"tickets_scope"=>"1", "changes_scope"=>"8", "solutions_scope"=>"15"}
scope_value.values.map { |i| 2** i.to_i }.inject(0, :|)
I realised
scope_value.values.map {|i| 2** i.to_i }.sum
does the the same thing as well
In terms of functionality doesn't both lines of code do the same thing. Is there any advantage to using sum over the other in terms of performance.
Yes, these two snippets produce identical results.
No, not at all. In fact,
0is irrelevant here. You can omit it and still get the same result.Operations in these two snippets are very different. They only produce the same result because of special shape of your data. Which is "each number has only one bit set and no two numbers have the same bit set". Violate this rule and see results diverge.
BTW, before we had
.sum, we used to emulate it with.inject(:+). This does the same thing (when used on integer arrays)