什么是破坏性的? [英] What is destructive?

查看:239
本文介绍了什么是破坏性的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Ruby有很多方法,尤其是在数组或类似对象的数组上,例如sortflatten.但是,这些方法也具有孪生子(带有感叹号的孪生子),例如sort!flatten!.

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!.

现在我的问题是:

  • flattenflatten!(破坏性展平)之间有什么区别?
  • 一个更普遍的问题,为什么将其称为破坏性的?
  • What is the difference between flatten and flatten! (destructive flatten)?
  • A more general question, why is it called destructive?

推荐答案

区别仅在于flatten返回数组的副本(被展平的新数组),而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.

正如@padde所指出的那样,由于破坏性的操作可能会消耗更少的内存,因为结构可能很大,并且复制会很昂贵.

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.

这里是使用sortsort!的示例.

a = [9, 1, 6, 5, 3]
b = a.sort
c = [7, 6, 3]
c.sort!

内容:

a = [9, 1, 6, 5, 3]
b = [1, 3, 5, 6, 9]
c = [3, 6, 7]

这篇关于什么是破坏性的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆