为什么在 Ruby 方法中使用感叹号? [英] Why are exclamation marks used in Ruby methods?
问题描述
在 Ruby 中,有些方法有一个问号 (?
),它会问像 include?
这样的问题,询问是否包含有问题的对象,然后返回一个 true/假.
In Ruby some methods have a question mark (?
) that ask a question like include?
that ask if the object in question is included, this then returns a true/false.
但是为什么有些方法有感叹号 (!
) 而其他方法没有?
But why do some methods have exclamation marks (!
) where others don't?
什么意思?
推荐答案
一般来说,以 !
结尾的方法表示该方法将修改调用它的对象.Ruby 将这些称为危险方法",因为它们会更改其他人可能引用的状态.下面是一个简单的字符串示例:
In general, methods that end in !
indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to. Here's a simple example for strings:
foo = "A STRING" # a string called foo
foo.downcase! # modifies foo itself
puts foo # prints modified foo
这将输出:
a string
在标准库中,您会在很多地方看到成对的名称相似的方法,一个带有 !
,另一个没有.没有的被称为安全方法",它们返回原始的副本,并将更改应用于副本,而被调用者不变.这是没有 !
的相同示例:
In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the !
and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the !
:
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 类都遵循它.它还可以帮助您跟踪代码中的修改内容.
Keep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.
这篇关于为什么在 Ruby 方法中使用感叹号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!