本文介绍了“!"的目的是什么?和“?"在方法名称的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时我在Ruby中看到带有?"的方法和 "!"在它们的末尾,例如:
Sometimes I see methods in Ruby that have "?" and "!" at the end of them, e.g:
name = "sample_string"
name.reverse
name.reverse!
name.is_binary_data?
我想知道他们的目的是什么?它们只是语法糖衣吗?
I was wondering what their purpose is? Are they just syntax sugarcoating?
推荐答案
出于可读性考虑,它只是糖衣",但它们确实具有共同的含义:
It's "just sugarcoating" for readability, but they do have common meanings:
- 以
!
结尾的方法会执行某些永久性或潜在危险的更改;例如:-
Enumerable#sort
返回对象的排序版本,而Enumerable#sort!
对其进行排序. - 在Rails中,如果保存失败,
ActiveRecord::Base#save
返回false,而ActiveRecord::Base#save!
引发异常. -
Kernel::exit
导致脚本退出,而Kernel::exit!
立即退出脚本,绕过所有退出处理程序.
- Methods ending in
!
perform some permanent or potentially dangerous change; for example:Enumerable#sort
returns a sorted version of the object whileEnumerable#sort!
sorts it in place.- In Rails,
ActiveRecord::Base#save
returns false if saving failed, whileActiveRecord::Base#save!
raises an exception. Kernel::exit
causes a script to exit, whileKernel::exit!
does so immediately, bypassing any exit handlers.
在您的示例中,
name.reverse
求值为反向字符串,但仅在name.reverse!
行之后,name
变量才实际包含反向名称.name.is_binary_data?
看起来像是"name
二进制数据吗?".In your example,
name.reverse
evaluates to a reversed string, but only after thename.reverse!
line does thename
variable actually contain the reversed name.name.is_binary_data?
looks like "isname
binary data?".这篇关于“!"的目的是什么?和“?"在方法名称的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
-