Ask Your Question
3

Which one is preferable in Ruby/Rails - sum or reduce(:+)? Besides speed, what factors should be taken into account?

asked 2021-12-15 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-06-02 12:00:00 +0000

david gravatar image

Both sum and reduce(:+) methods are effective when it comes to adding values in arrays. It mostly depends on personal preference and readability. However, here are some factors one could consider:

  1. Readability: sum method is more straightforward and easier to read. It clearly conveys the intention of adding values in an array.

  2. Nil Handling: If the array contains nil values, sum method throws a TypeError. In contrast, reduce(:+) handles nil values gracefully by returning 0.

  3. Custom Operations: The reduce(:+) method can be more flexible in terms of custom operations. For example, if one needs to multiply the values instead of summing them up, it can be easily achieved using reduce.

  4. Performance: Generally, the reduce method is faster than sum method as it avoids creating an intermediate array, but the difference is often negligible in small arrays.

So, in conclusion, sum method is simpler and more readable, while reduce(:+) method is more flexible and efficient.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-15 11:00:00 +0000

Seen: 7 times

Last updated: Jun 02 '22