Ruby methods are supposed to end in a name with ?
.
In fact, built-in classes have methods such as String # empty? and Array # include?. It is customary to name the predicate method, that is, the method for using the truth / falseness of the return value. This is a convention, not a rule.
by the way,
Ruby true/false is different from true/false-Qiita
As I wrote in, Ruby does not always use true
/ false
to indicate true/false.
In fact, some built-in predicate methods return something other than true
/ false
.
For example, String # casecmp? ignores the difference between uppercase and lowercase letters and judges a match. Basically, it returns true
/ false
, but when the string encoding is incompatible. Is designed to return nil
.
If the "predicate method" is a "method for using the authenticity of the return value", the delineation is somewhat ambiguous because it is not the specification of the method itself but the purpose of the user. I am thinking.
For example, Regexp # match returns a MatchData object if it finds a substring that matches itself in its arguments, otherwise it returns nil
, but in Ruby 2.4 [Regexp # match] Until #match?](https://docs.ruby-lang.org/ja/3.0.0/method/Regexp/i/match=3f.html) appeared
if /\d/.match(str)
#And so on
end
It was sometimes used in such situations. It can be said that this was exactly the usage as a predicate method.
Recommended Posts