I know that Ruby has many methods, especially on array or array like objects, for example sort
or flatten
. However, these methods also have a twin (the one with an exclamation mark) like sort!
and flatten!
.
Now my questions are:
flatten
and flatten!
(destructive flatten)?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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With