Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is destructive?

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:

  • What is the difference between flatten and flatten! (destructive flatten)?
  • A more general question, why is it called destructive?
like image 215
Prem Avatar asked Dec 27 '22 03:12

Prem


1 Answers

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]
like image 144
squiguy Avatar answered Jan 11 '23 00:01

squiguy