TL;DR#
- Be careful about
truevs truthy on the boundaries of your application - Consider returning
trueandfalseexclusively in predicate methods - Consider testing
.to eq trueinstead of.to be_truthyinRSpec
Truthiness in Ruby#
Ruby, being duck-typed, does not strictly enforce "boolean" values:
if value
do_this
else
do_that
endIn this case, we don't care if value is true or false or 1 or 0 or a complex object. Ruby has a method for determining if any kind of value is "truthy" or "falsey". For Ruby, the rules are fairly lean:
nilis falseyfalseis falsey- Everything else is truthy
Therefore:
"Hello World" if 1 # => "Hello World"
"Hello World" if nil # => nilNow there might be some surprises if you come from other languages:
"Hello World" if "" # => "Hello World"
"Hello World" if 0 # => "Hello World"Those wouldn't fly in all languages, but that's fine...unless...
Project Boundaries#
Let's contrive a thing to make a point:
class ContrivedThing < ApplicationRecord
def self.foo
where(id: all.select(&:foo?))
end
def foo?
complicated_foo?
end
private
def complicated_foo?
# ... do complex work ...
complicated_derived_thing =~ /fancy regex/
end
endAnd we can test it like:
expect(contrived_thing).to be_fooBut there could be a problem! What if we have lots of ContrivedThings? all.select(&:foo?) loads all the records into memory, does a complicated calculation on each to determine which are foo?-ey, and then wraps them in a huge binds list for query chaining.As much as possible, we'd like to keep this in SQL so we decide to memoize the value of foo? in a boolean column named foo in the database:class ContrivedThing < ApplicationRecord before_save :memoize_foo private def memoize_foo return unless certain_things_changed? assign_attributes(foo: complicated_foo?) endendNow we can delete ContrivedThing::foo and ContrivedThing#foo? (because ActiveRecord will create scopes and predicate methods for
boolean columns) and we've vastly improved the performance of the scope.
But there's a catch...
The Truth of Truthiness#
We've been using foo? as a truthy/falsey identifier but what is it actually? Well its return value comes from the =~ operator which returns integer or nil.
So we might have:
"string" =~ /string/ # => 0which is properly truthy in Ruby because there was a match. Unfortunately, we're directly serializing that value to our postgresql database which coerces zero to false.Now we have a bunch of values that used to be truthy in Ruby but now are falsey because postgres converted them to a strict false value.
How Could We Avoid This?#
Carefully Considering the Destination#
One approach involves converting the value before we head off to the database:
def memoize_foo
return unless certain_things_changed?
boolean_value = ActiveModel::Type::Boolean.new.cast(complicated_foo?)
# Rails 4.2 - ActiveRecord::Type::Boolean.new.type_cast_from_database()
# Rails 4.1 and below - ActiveRecord::ConnectionAdapters::Column.value_to_boolean
assign_attributes(foo: boolean_value)
endWhich works wonderfully, but can be forgotten and is only really caught if you happened to write a test like:
thing = ContrivedThing.new()
# setup to allow complicated_foo? to return 0
thing.save
expect(thing).to be_fooEnsure Boolean Values in Predicate Methods#
There's clearly some heat around this topic in general but the official Ruby FAQ recommends:
predicate methods (those whose name ends with a question mark) return true or false.
So one way around our bug is:
def complicated_foo?
complicated_derived_thing =~ /fancy regex/ ? true : false # => true/false
endEnsure Boolean Values in Tests#
Following the above option, what if our original test wasn't:
expect(contrived_thing).to be_foobut instead:
expect(contrived_thing.foo?).to eq trueThis sort of testing isn't nearly as pretty, but helps prevent these integration pains.
Is 0 truthy in Ruby, and which values differ in JavaScript and Python?#
Yes, 0 is truthy in Ruby, and "Those wouldn't fly in all languages": JavaScript and Python both treat 0 and the empty string as false. Only Python also treats an empty array or list and an empty hash or dict as false. The Ruby 4.0 docs explain the rule. "For the tests in these control expressions, nil and false are false-values and true and any other object are true-values."
| Value | Ruby | JavaScript | Python |
|---|---|---|---|
| false | falsy | falsy | falsy |
| nil, null or None | falsy | falsy | falsy |
| 0 and 0.0 | truthy | falsy | falsy |
| Empty string | truthy | falsy | falsy |
| Empty array or list | truthy | truthy | falsy |
| Empty hash, object or dict | truthy | truthy | falsy |
| The string "0" | truthy | truthy | truthy |
MDN's lists of falsy values and truthy values cover the JavaScript column. The Python column follows the truth value testing section of the Python docs. In Ruby, {} is a hash. In JavaScript it is an object, and in Python it is a dict.
MDN calls its table "a complete list of JavaScript falsy values". Python's list adds "zero of any numeric type", so 0j is falsy too. MDN's truthy examples include the strings "0" and "false".
The Official Ruby FAQ says "in Ruby, only nil and false are false in conditional contexts." To test for an empty string, it says to use empty?, compare the string to an empty string, or compare its size or length to 0. The Ruby 4.0 docs for String#empty? say it "Returns whether the length of self is zero".
What do =~, match and match? return in Ruby?#
Of Ruby's match methods, "the =~ operator which returns integer or nil" does not return a boolean. match without a block returns "matchdata or nil" and match? returns "true or false", say the Ruby 4.0 docs. A match at the first character makes =~ return 0, and 0 is truthy in Ruby.
| Method | What the Ruby 4.0 docs say it returns | Regexp global variables |
|---|---|---|
| String#=~ | "integer or nil", with 'foo' =~ /f/ # => 0 | "updates Regexp-related global variables" |
| String#match | "matchdata or nil", with no block | "updates Regexp Global Variables" |
| String#match? | "true or false" | "does not update Regexp Global Variables" |
| Regexp#match? | "true or false" | "without updating $~ and other related variables" |
The docs show what that looks like on the string 'foo'. After 'foo' =~ /f/ returns 0, the global variable $~ holds #<MatchData "f">. After a miss, $~ is nil.
| Method | A hit | A miss |
|---|---|---|
| String#=~ | 'foo' =~ /o/ # => 1 | 'foo' =~ /x/ # => nil |
| String#match | 'foo'.match('o') # => #<MatchData "o"> | 'foo'.match('x') # => nil |
| String#match? | 'foo'.match?(/o/) # => true | 'foo'.match?(/x/) # => false |
The code in this post ends its match with ? true : false. match? gives a true or false directly, for example /fancy regex/.match?(complicated_derived_thing).
Use =~ when you need the position of a match. Use match when you need the MatchData object. Use match? when you need a plain true or false.
Do Ruby methods ending in ? always return true or false?#
No: "There's clearly some heat around this topic in general", and some Ruby core methods that end in a question mark return other values. The Official Ruby FAQ says "We recommend that predicate methods (those whose name ends with a question mark) return true or false." Its next sentence reads "Other methods that need to indicate failure should return nil."
| Method | What the Ruby 4.0 docs say it returns |
|---|---|
| Numeric# | "self or nil". It "Returns self if self is not a zero value, nil otherwise". |
| Float#infinite? | "-1, 1, or nil" |
| File.size? | "Integer or nil". It "Returns nil if file_name doesn’t exist or has zero size, the size of the file otherwise." |
These methods still work in a condition. A number or a size is truthy, and nil is falsy.
The community Ruby Style Guide says "The names of predicate methods (methods that return a boolean value) should end in a question mark". It adds "Methods that don't return a boolean, shouldn't end in a question mark." RuboCop has cops that check both sides of that rule. The next table shows RuboCop 1.92.2, the latest release on RubyGems as of November 16, 2026, published October 29, 2026.
| Rule or cop | What its docs say | Status in RuboCop 1.92.2 |
|---|---|---|
| Predicate Methods Suffix | "The names of predicate methods (methods that return a boolean value) should end in a question mark" | Style guide text only |
| Style/ | "Checks for predicate method definitions that return nil" | Pending, added in 1.53 |
| Naming/ | "Checks that predicate methods end with ? and non-predicate methods do not" | Pending, added in 1.76 |
| Naming/ | "Checks that predicate method names end with a question mark and do not start with a forbidden prefix" | Enabled by default, added in 0.50 |
The status column comes from RuboCop's default configuration. Its comment says pending cops are "not enabled by default with warning message". The same comment says to change this by overriding either NewCops: enable or NewCops: disable. When NewCops is enable, "pending cops are enabled in bulk".
Naming/PredicateMethod runs in conservative mode by default. That mode "allows a method to be named with a question mark as long as at least one return value is boolean". In aggressive mode, "methods with a question mark will register an offense if any known non-boolean return values are detected." The default configuration also lists infinite? and nonzero? under WaywardPredicates, the same two core methods as in the table above.
One of the Naming/PredicateMethod cop's bad examples is def foo? 5 end, a method that ends in a question mark and returns a literal. Its source file says the cop "does not make an assessment if the return type is unknown (non-predicate method calls, variables, etc.)." This post's complicated_foo? returns the result of =~, a method whose name has no question mark. The source file for Style/ReturnNilInPredicateMethodDefinition lists return nil if condition inside def foo? as bad code. Its docs mark autocorrection as unsafe because it changes the return value from nil to false.
How do be_truthy, be true and predicate matchers differ in RSpec?#
be_truthy passes for any value that is not nil or false, and be true passes only for the true object itself. A be_foo matcher calls foo? and, by default, accepts a truthy result. eq(true) passes when actual == true.
| Matcher | What RSpec's docs say it passes on |
|---|---|
| be_ | "passes if actual is truthy (not nil or false)" |
| be true | "passes if actual == true". It runs be(true), and be(expected) "passes if actual.equal?(expected)" |
| eq(true) | "passes if actual == expected", with true as the expected value |
| be_ | "passes if actual is falsy (nil or false)" |
| be false | "passes if actual == false". It runs be(false), and be(expected) "passes if actual.equal?(expected)" |
| be_ | It calls the predicate method. "Simply prefix the method with be_ and remove the question mark." |
The built-in matchers list is the source for the be_truthy, eq(true) and be_falsey rows. The RSpec expectations README is the source for the be true and be false rows. Its lines for them say "passes if actual == true" and "passes if actual == false". Its line for be(expected) says "passes if actual.equal?(expected)", and be true and be false are that matcher with true or false as the expected value. The predicate matchers page is the source for the last row.
RSpec has a setting for strictness, named strict_predicate_matchers. Its comment says it "Configures RSpec to check predicate matchers to be(true) / be(false) (strict), or be_truthy / be_falsey (not strict)." It adds "Historically, the default was false, but true is recommended." The default depends on the release.
| Release | Strict setting default | Published |
|---|---|---|
| rspec-expectations 3.13.6 | false | November 6, 2026 |
| rspec-expectations 4.0.0.beta1 | true | February 18, 2026 |
Version 3.13.6 is the latest release on RubyGems as of November 16, 2026. Version 4.0.0.beta1 is a prerelease.
To turn strict matching on, set expectations.strict_predicate_matchers = true inside config.expect_with :rspec do |expectations|. The predicate matchers page shows that block. Its example uses a has_strange_result? method that returns 42. The example passes with non-strict matchers, which the page marks as the default, and is a deliberate failure with strict matchers.
This post's TL;DR says "Consider testing .to eq true instead of .to be_truthy in RSpec". Strict mode makes predicate matchers check for be(true) or be(false), in the words of its own comment.
Summary#
- Ruby's handling of predicate methods, predicate matchers, and truthy/falsey
values allows for light, expressive, pleasing code, but can result in subtle
bugs when interacting with outside sources. - Be extra careful at application boundary points that there are no assumptions
about how languages interpret different values. - When in doubt, be overly specific to ensure values can't be misunderstood.
Learn more about how The Gnar builds Ruby on Rails applications.


