为什么是替换而不是替换!对于 ruby 中的字符串?
Why is it replace not replace! for strings in ruby?
replace
改变当前字符串而不是返回一个新实例。为了与 Ruby 中的其他方法保持一致,似乎应该称为 replace!
这是 bug/inconsistency 还是我遗漏了什么?
没有。每当您想要一个与另一个现有字符串没有任何关系的新字符串时,从现有字符串创建新字符串是没有意义的。例如,假设有一个 String
方法 create_new_string
通过用给定参数替换内容来从现有字符串创建一个新的字符串实例,如下所示:
"foo".create_new_string("bar")
# => "bar"
很容易看出这没有意义。您可以而且应该使用字符串文字创建一个新字符串:
"bar"
# => "bar"
因此,String
方法通过替换其内容以破坏性方式创建新字符串是没有意义的;一个有意义的方法可以替换字符串的内容,应该破坏性地替换接收字符串的内容,并且 return 该字符串毫无意外。因此,不需要爆炸。
来自 matz 的 post 这里 https://www.ruby-forum.com/topic/176830#773946
The bang (!) does not mean "destructive" nor lack of it mean non
destructive either. The bang sign means "the bang version is more
dangerous than its non bang counterpart; handle with care". Since
Ruby has a lot of "destructive" methods, if bang signs follow your
opinion, every Ruby program would be full of bangs, thus ugly.
所以最初的问题来自对 bang (!
) 含义的误解。没有爆炸,因为只有一个 replace
方法才有意义,因此无需将其标记为 "more dangerous".
replace
改变当前字符串而不是返回一个新实例。为了与 Ruby 中的其他方法保持一致,似乎应该称为 replace!
这是 bug/inconsistency 还是我遗漏了什么?
没有。每当您想要一个与另一个现有字符串没有任何关系的新字符串时,从现有字符串创建新字符串是没有意义的。例如,假设有一个 String
方法 create_new_string
通过用给定参数替换内容来从现有字符串创建一个新的字符串实例,如下所示:
"foo".create_new_string("bar")
# => "bar"
很容易看出这没有意义。您可以而且应该使用字符串文字创建一个新字符串:
"bar"
# => "bar"
因此,String
方法通过替换其内容以破坏性方式创建新字符串是没有意义的;一个有意义的方法可以替换字符串的内容,应该破坏性地替换接收字符串的内容,并且 return 该字符串毫无意外。因此,不需要爆炸。
来自 matz 的 post 这里 https://www.ruby-forum.com/topic/176830#773946
The bang (!) does not mean "destructive" nor lack of it mean non destructive either. The bang sign means "the bang version is more dangerous than its non bang counterpart; handle with care". Since Ruby has a lot of "destructive" methods, if bang signs follow your opinion, every Ruby program would be full of bangs, thus ugly.
所以最初的问题来自对 bang (!
) 含义的误解。没有爆炸,因为只有一个 replace
方法才有意义,因此无需将其标记为 "more dangerous".