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
!
Are destructiveIt 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
!
Are destructiveIt 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