The difference is simply that flatten
returns a copy of the array (a new array that is flattened) and flatten!
does the modification "in place" or "destructively." The term destructive means that it modifies the original array. This is useful for when you know what you want your end result to be and don't mind if the original structure gets changed.
As @padde pointed out, it will consume less memory as well to perform something destructively since the structure could be large and copying will be expensive.
However, if you want to keep your original structure it is best to use the method and make a copy.
Here is an example using sort
and sort!
.
a = [9, 1, 6, 5, 3]
b = a.sort
c = [7, 6, 3]
c.sort!
Contents:
a = [9, 1, 6, 5, 3]
b = [1, 3, 5, 6, 9]
c = [3, 6, 7]