在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 on Rails (RoR)模型验证上下文中带有感叹号/shebangs的Ruby方法的重要性。

本质上,无论何时开发人员定义模型验证(此处解释),他们的最终目标都是拒绝数据库记录更改,并在提交了无效数据以更新相关记录的情况下引发/抛出相关异常。

RoR ActiveRecord gem定义了各种模型操作方法(Ruby on Rails指南)。在这些方法中,有效的?方法是唯一一个无需数据库操作/修改就能触发验证的方法。其余的方法尝试更改数据库。

这些方法在运行时触发回调。列表中的一些方法有一个带shebang的姐妹方法。这两者之间有什么区别?它与记录验证失败时返回的回调形式有关。

不带感叹号/shebang的方法在记录验证失败时只返回布尔值false,而带shebang的方法会引发/抛出异常,然后可以在代码中适当地处理。

通常,以!结尾的方法指示该方法将修改调用它的对象。Ruby将这些方法称为“危险方法”,因为它们更改了其他人可能引用的状态。下面是一个简单的字符串示例:

foo = "A STRING"  # a string called foo
foo.downcase!     # modifies foo itself
puts foo          # prints modified foo

这将输出:

a string

在标准库中,您可以在很多地方看到名称相似的方法对,其中一个带有!一个没有。没有安全方法的方法被称为“安全方法”,它们返回原始方法的副本,其中对副本进行了更改,而被调用者没有更改。下面是没有使用!的相同示例:

foo = "A STRING"    # a string called foo
bar = foo.downcase  # doesn't modify foo; returns a modified string
puts foo            # prints unchanged foo
puts bar            # prints newly created bar

这个输出:

A STRING
a string

请记住,这只是一种约定,但许多Ruby类都遵循它。它还可以帮助您跟踪代码中修改的内容。

!

我喜欢把这看作是一个爆炸性的变化,它摧毁了之前的一切。Bang或感叹号表示您正在对代码进行永久保存的更改。

如果你使用Ruby的方法进行全局替换,sub!你所做的替换是永久的。

你可以想象的另一种方式是,打开一个文本文件,进行查找和替换,然后保存。! 在代码中执行相同的操作。

如果您来自bash世界,另一个有用的提醒是sed -i具有永久保存更改的类似效果。

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

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]

简单的解释:

foo = "BEST DAY EVER" #assign a string to variable foo.

=> foo.downcase #call method downcase, this is without any exclamation.

"best day ever"  #returns the result in downcase, but no change in value of foo.

=> foo #call the variable foo now.

"BEST DAY EVER" #variable is unchanged.

=> foo.downcase! #call destructive version.

=> foo #call the variable foo now.

"best day ever" #variable has been mutated in place.

但是如果你曾经用downcase来调用一个方法!在上面的解释中,foo将永久地更改为downcase。downcase !不会返回一个新的字符串对象,而是在适当的位置替换字符串,完全将foo更改为downcase。 我建议你不要用小写!除非完全有必要。