Question

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?
Was it helpful?

Solution

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]

OTHER TIPS

Array#flatten:- Returns a new array that is a one-dimensional flattening of self (recursively).

Array#flatten!:- Flattens self in place.

a = [1,2,[3,4]]
p a.object_id #=> 74502050
p a.flatten.object_id #=> 74501960
p a.flatten!.object_id #=> 74502050

flatten creates a new array object, as a.flatten.object_id shows a different value from a.object_id.

flatten! modifies the object that a references, which a.flatten!.object_id shows as 74502050.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top