The presence or absence of! In Ruby method names does not mean destructive / non-destructive

One of the myriad misconceptions in Ruby beginners articles is about the ! At the end of the method name. There are several variations of mistakes, but the most extreme ones

It will be.

When a method is destructive, it changes the object that is the receiver. For example

"Ruby".upcase

In the case of, the upcase method is non-destructive and does not change the receiver. Instead, it creates and returns a new String object that is capitalized from the receiver and has a content of "RUBY".

on the other hand,

"Ruby".upcase!

In the case of, no new object is created and the contents of the receiver itself are capitalized. The return value is self if the conversion was actually done (if it contained any lowercase letters), otherwise it is nil.

Exactly in this example

It has become. This is a source of misunderstanding, isn't it?

Certainly, there are many sets of built-in methods in Ruby that have a destructive version and a non-destructive version paired, and differ only in the presence or absence of ! At the end of the method name.

However, this is just such a name, not a Ruby specification.

Also, there are many built-in methods that are destructive without the !. For String, such as concat or force_encoding. For Array, it's shift or push.

Also, a pair of naming methods that differ only in the presence or absence of ! Is not necessarily a destructive / non-destructive version. Rails is familiar with ActiveRecord's create!/Create.

Recommended Posts

The presence or absence of! In Ruby method names does not mean destructive / non-destructive
[Rails] Regarding the presence or absence of parentheses in the argument of the render method
The difference between puts and print in Ruby is not just the presence or absence of line breaks
Call a method of the parent class by explicitly specifying the name in Ruby
[Order method] Set the order of data in Rails
[Java] Handling of JavaBeans in the method chain
@BeforeStep does not work in Tasklet of spring-batch
Count the number of occurrences of a string in Ruby
[Ruby] The role of subscripts in learning elements in arrays
Examine the elements in the array using the [Ruby] includes? Method
Correspondence when Ruby version does not switch in rbenv
Get the URL of the HTTP redirect destination in Ruby
[Ruby] Get in the habit of using the dup method when making a copy of a string variable
[Ruby] Thinking when there is no receiver in front of the method (it looks like)