Difference Between downcase and downcase! in Ruby

断了今生、忘了曾经 提交于 2019-12-17 19:35:03

问题


I am just learning Ruby and I don't quite understand the difference between several Ruby methods with and without a '!' at the end. What's the difference? Why would I use one over the other?


回答1:


Methods with an exclamation mark at the end are often called bang-methods. A bang method doesn't necessarily modify its receiver as well as there is no guarantee that methods without a exclamation mark doesn't.

It's all very well explained in this blog post. To quote the post:

The ! in method names that end with ! means, “This method is dangerous”—or, more precisely, this method is the “dangerous” version of an otherwise equivalent method, with the same name minus the !. “Danger” is relative; the ! doesn’t mean anything at all unless the method name it’s in corresponds to a similar but bang-less method name.

and

The ! does not mean “This method changes its receiver.” A lot of “dangerous” methods do change their receivers. But some don’t. I repeat: ! does not mean that the method changes its receiver.




回答2:


The non-bang downcase() method simply returns a new object representing you string downcased.

The bang version modifies your string itself.

my_text = "MY TEXT"
my_new_text = my_text.downcase
puts my_new_text # will print out "my text"
puts my_text     # will print out "MY TEXT" - the non-bang method doesn't touch it

my_text.downcase!

puts my_text # will print out "my text". The bang version has modified the object you're calling the method on


来源:https://stackoverflow.com/questions/709229/difference-between-downcase-and-downcase-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!