为什么在Ruby方法中使用感叹号? [英] Why are exclamation marks used in Ruby methods?
问题描述
在Ruby中,某些方法带有问号(?
),它会问类似include?
的问题,询问是否包含所讨论的对象,然后返回true/false.
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屋!