Skip to main content
Published in Engineering Insights

When Systems Can't Agree on the Truth

When Systems Can't Agree on the Truth
Table of contents
  1. TL;DR
  2. Truthiness in Ruby
  3. Project Boundaries
  4. The Truth of Truthiness
  5. How Could We Avoid This?
    1. Carefully Considering the Destination
    2. Ensure Boolean Values in Predicate Methods
    3. Ensure Boolean Values in Tests
  6. Is 0 truthy in Ruby, and which values differ in JavaScript and Python?
  7. What do =~, match and match? return in Ruby?
  8. Do Ruby methods ending in ? always return true or false?
  9. How do be_truthy, be true and predicate matchers differ in RSpec?
  10. Summary

TL;DR#

  • Be careful about true vs truthy on the boundaries of your application
  • Consider returning true and false exclusively in predicate methods
  • Consider testing .to eq true instead of .to be_truthy in RSpec

Truthiness in Ruby#

Ruby, being duck-typed, does not strictly enforce "boolean" values:

Ruby
if value
  do_this
else
  do_that
end

In 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:

  • nil is falsey
  • false is falsey
  • Everything else is truthy

Therefore:

Ruby
"Hello World" if 1   # => "Hello World"
"Hello World" if nil # => nil

Now there might be some surprises if you come from other languages:

Ruby
"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:

Ruby
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
end

And we can test it like:

Ruby
expect(contrived_thing).to be_foo

But 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:

Ruby
"string" =~ /string/ # => 0

which 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:

Ruby
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)
end

Which works wonderfully, but can be forgotten and is only really caught if you happened to write a test like:

Ruby
thing = ContrivedThing.new()
# setup to allow complicated_foo? to return 0
thing.save
expect(thing).to be_foo

Ensure 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:

Ruby
def complicated_foo?
  complicated_derived_thing =~ /fancy regex/ ? true : false # => true/false
end

Ensure Boolean Values in Tests#

Following the above option, what if our original test wasn't:

Ruby
expect(contrived_thing).to be_foo

but instead:

Ruby
expect(contrived_thing.foo?).to eq true

This 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."

ValueRubyJavaScriptPython
falsefalsyfalsyfalsy
nil, null or Nonefalsyfalsyfalsy
0 and 0.0truthyfalsyfalsy
Empty stringtruthyfalsyfalsy
Empty array or listtruthytruthyfalsy
Empty hash, object or dicttruthytruthyfalsy
The string "0"truthytruthytruthy

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.

MethodWhat the Ruby 4.0 docs say it returnsRegexp 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.

MethodA hitA 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."

MethodWhat the Ruby 4.0 docs say it returns
Numeric#nonzero?"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 copWhat its docs sayStatus 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/ReturnNilInPredicateMethodDefinition"Checks for predicate method definitions that return nil"Pending, added in 1.53
Naming/PredicateMethod"Checks that predicate methods end with ? and non-predicate methods do not"Pending, added in 1.76
Naming/PredicatePrefix"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.

MatcherWhat RSpec's docs say it passes on
be_truthy"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_falsey"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_fooIt 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.

ReleaseStrict setting defaultPublished
rspec-expectations 3.13.6falseNovember 6, 2026
rspec-expectations 4.0.0.beta1trueFebruary 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.

Frequently asked questions

Which values are falsey in Ruby?

Only nil and false are falsey. Zero and an empty string are both truthy.

Why did the regular expression result cause a bug?

The =~ operator returns an integer or nil. A match at the start of the string returns zero, which is truthy in Ruby. In the example, the database converts that zero to false.

How can a predicate return a strict boolean?

The example puts the regular expression match in a conditional expression ending in ? true : false. That makes complicated_foo? return true or false rather than an integer or nil.

What test helps catch this mismatch?

Use expect(contrived_thing.foo?).to eq true instead of expect(contrived_thing).to be_foo. The explicit check tests for true rather than accepting any truthy result.

Is an empty array truthy in Ruby?

Yes. In Ruby, nil and false are false-values and any other object is a true-value, so [] and {} are both truthy. JavaScript also treats [] as truthy. Python treats an empty list as false.

What does match? return in Ruby?

String#match? and Regexp#match? return true or false, according to the Ruby 4.0 docs. Unlike =~, which returns an integer or nil, they do not update Regexp global variables such as $~.

What is the difference between be_truthy and be true in RSpec?

be_truthy passes when the value is truthy, meaning not nil or false, so 0 passes. be true passes only for the true object itself. The RSpec expectations README says be(expected) "passes if actual.equal?(expected)", and be true is be(true).

Can The Gnar Company upgrade an old Ruby on Rails app?

Yes. The Gnar Company upgrades existing Rails apps, and a good first step is a code audit. Gnar can sign an NDA before it reads your code. Senior engineers send back a ranked list of the risks, the easy fixes and your realistic options.

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.