A side effect is anything a method does beyond returning a value. Mutating an object, printing output, and raising an exception are all side effects; they may be intentional or accidental. section 16.1.1
A summation that consumes its input
This method sums an array by removing its elements with shift. The first call can return the expected sum, but it leaves the array empty, so a later call returns a different result. section 16.1.1
def sum_of_parts(arr)
sum = 0
arr.size.times { sum = sum + arr.shift }
sum
end
The method changes the array it receives while accumulating the sum. section 16.1.1
Using reduce instead avoids changing the input array, so repeated calls return the same result. Other Ruby methods mutate in place too: upcase! changes a string, while array append with << and hash deletion can change state without a bang suffix. Exceptions and console output are side effects as well. Side effects are not always wrong—programs sometimes need to change state—but recognizing them helps distinguish stateful methods from pure ones. section 16.1.1 section 16.1.3 section 7.3.1























