ruby - What is destructive? -


i know ruby has many methods, on array or array objects, example sort or flatten. however, these methods have twin (the 1 exclamation mark) sort! , flatten!.

now questions are:

  • what difference between flatten , flatten! (destructive flatten)?
  • a more general question, why called destructive?

the difference flatten returns copy of array (a new array flattened) , flatten! modification "in place" or "destructively." term destructive means modifies original array. useful when know want end result , don't mind if original structure gets changed.

as @padde pointed out, consume less memory perform destructively since structure large , copying expensive.

however, if want keep original structure best use method , make copy.

here example using sort , 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] 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -