数组爆炸方法行为 [英] Behaviour of Array bang methods

查看:187
本文介绍了数组爆炸方法行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阵的一些爆炸版本方法是像紧凑!拒绝!压扁! uniq的!收益如果未进行任何更改:

Some bang version of Array methods are like compact!, reject!, flatten!, uniq! return nil if no changes were made:

[1,[2]].flatten!
# => [1, 2]
[1,2].flatten!
# => nil
[1,[2]].flatten
# => [1, 2]
[1,2].flatten
# => [1, 2]

[1,2,nil].compact!
# => [1, 2]
[1,2].compact!
# => nil
[1,2,nil].compact
# => [1, 2]
[1,2].compact
# => [1, 2]

如果他们这样做了,必须有一个原因。任何想法可能是什么?

If they did it this way, there has to be a reason. Any ideas what it might be?

推荐答案

咣()的方法做修改的地方当前对象,但他们返回如果每个没有受影响的元素文档的。如果出于某种原因,你需要做的东西,如果你做了修改所涉及的阵列,这非常有用。

The bang (!) methods do modify the current object in place, but they do return nil if there are no affected elements per the documentation. This is useful if, for whatever reason, you need to do something if you did modify the array in question.

if array.flatten!
  puts "Oh yeah... flattened that array!"
end

这篇关于数组爆炸方法行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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