In Ruby, methods with? Do not always return true/false.

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

In Ruby, methods with? Do not always return true/false.
Do not return when memoizing in Ruby
Ruby methods often used in Rails
Ignore parameters that do not exist in the model with ObjectMapper # readValue
Be careful when omitting return in Ruby
Do not use instance variables in partial
must not return in the for statement
Methods that I found useful in Ruby
Ruby methods return the last evaluated value
Do not accept System.in in gradle run
Return custom object with @Query in spring-data-jpa
Do not declare variables in List in Java
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
[Ruby] Methods that can be used with strings
Visualize test methods running in TestNG with listeners
rbenv versions and ruby -v versions do not match