在Ruby中,有些方法带有问号(?),会问include?询问是否包含有问题的对象,然后返回true/false。

但是为什么有些方法有感叹号(!)而其他方法没有呢?

这是什么意思?


当前回答

被称为“破坏性方法”,它们倾向于改变你所引用的对象的原始副本。

numbers=[1,0,10,5,8]
numbers.collect{|n| puts n*2} # would multiply each number by two
numbers #returns the same original copy
numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
numbers   # returns [nil,nil,nil,nil,nil]

其他回答

提醒一下,因为我自己也经历过。

在Ruby中,!改变对象并返回它。否则它将返回nil。

因此,如果你正在对一个数组进行某种操作,并调用方法.compact!没有东西要压缩,它会返回nil。

例子:

arr = [1, 2, 3, nil]
arr.compact!
=> [1, 2, 3]

Run again arr.compact!
=> nil

如果你需要在一行中使用数组arr,最好再次显式返回它,否则你将得到nil值。

例子:

arr = [1, 2, 3]
arr.compact! => nil
arr # to get the value of the array

! 通常意味着方法作用于对象而不是返回结果。摘自《Programming Ruby》一书:

“危险的”或修改接收者的方法可能会以“!”结尾命名。

这个命名约定来自Scheme。

1.3.5命名约定 按照惯例,程序的名称 总是返回一个布尔值 通常以“?”结尾。这样的程序 称为谓词。 按照惯例,程序的名称 存储值到先前 已分配的位置(见3.4节) 通常以“!”结尾。这样的程序 叫做变异程序。通过 方法返回的值 突变过程未指明。

被称为“破坏性方法”,它们倾向于改变你所引用的对象的原始副本。

numbers=[1,0,10,5,8]
numbers.collect{|n| puts n*2} # would multiply each number by two
numbers #returns the same original copy
numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
numbers   # returns [nil,nil,nil,nil,nil]

从themomorohoax.com:

刘海有以下几种用法,依我个人喜好而定。

如果活动记录方法没有这样做,则会引发错误 就像它说的那样。 活动记录方法保存记录或方法保存 对象(例如strip!) 方法做一些“额外的”事情,比如张贴到某个地方 一些行动。

关键是:只有在你真正想过是否要使用爆炸的时候 这是必要的,可以省去其他开发人员不得不这样做的烦恼 检查你为什么要使用爆炸声。

爆炸为其他开发者提供了两个线索。

方法调用后,没有必要保存对象 方法。 当你调用这个方法时,db会被改变。