What is destructive?

点点圈 提交于 2019-12-06 02:06:47

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]
Arup Rakshit

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!