C-like bit flags in Ruby

3 min read Original article ↗
- ruby

I recently needed some C-like bit flags in Ruby. There’s the bit_flag gem for this, but I didn’t particularly like its API. I also don’t think such a small feature justifies taking on a dependency. So I decided to roll my own. This is how it works:

Permission = BitFlags.for(:execute, :write, :read)

permissions = Permission.read | Permission.execute
Permission.read?(permissions)    #=> true
Permission.write?(permissions)   #=> false
Permission.execute?(permissions) #=> true

It also works quite nicely with Ruby’s pattern matching through the parse method:

case Permission.parse(int)
in [] then "none"
in [:execute, :write, :read] then "all"
in [:execute, :write] then "exactly execute and write"
in [*, :read, *] then "has read"
in [:execute] | [:write] then "only execute or write"
end

I shared this on Mastodon and people seemed to like it, so I’m releasing the code to the public domain:

# SPDX-License-Identifier: CC0-1.0
# See: https://creativecommons.org/publicdomain/zero/1.0/deed.en

class BitFlags
  def self.for(*names)
    values = names.each_with_index.to_h { |name, i| [name, 1 << i] }.freeze

    Class.new do
      define_singleton_method(:values) { values }

      values.each do |name, value|
        define_singleton_method(name) { value }
        define_singleton_method(:"#{name}?") { |int| int & value != 0 }
      end

      define_singleton_method(:parse) do |int|
        values.keys.filter { |flag| send(:"#{flag}?", int) }
      end
    end
  end
end

if __FILE__ == $0
  require "minitest/autorun"

  class TestFlags < Minitest::Test
    Permission = BitFlags.for(:execute, :write, :read)

    def test_values
      assert_equal({execute: 1, write: 2, read: 4}, Permission.values)
    end

    def test_accessors
      assert_equal 4, Permission.read
      assert_equal 2, Permission.write
      assert_equal 1, Permission.execute
    end

    def test_predicates
      permissions = Permission.read | Permission.execute
      assert Permission.read?(permissions)
      refute Permission.write?(permissions)
      assert Permission.execute?(permissions)
    end

    def test_parse
      permissions = Permission.read | Permission.execute
      assert_equal Permission.parse(permissions), [:execute, :read]
    end

    def test_pattern_matching_on_parse
      match = ->(int) {
        case Permission.parse(int)
        in [] then "none"
        in [:execute, :write, :read] then "all"
        in [:execute, :write] then "exactly execute and write"
        in [*, :read, *] then "has read"
        in [:execute] | [:write] then "only execute or write"
        end
      }

      assert_equal "none", match.call(0)
      assert_equal "all", match.call(7)
      assert_equal "exactly execute and write", match.call(3)
      assert_equal "has read", match.call(5)
      assert_equal "only execute or write", match.call(2)
    end
  end
end

You can also download the file and run the tests with ruby bit_flags.rb.

#Why not a gem?

You might be wondering why I decided not to release this as a gem. In short: I don’t think it’s worth it. The code is short and easy to understand. Copy it into your project, rename things as you see fit (maybe you’d rather call it FlagEnum), move the tests into a separate file if you want, and don’t worry about supply-chain security, random version constraints in a .gemspec, or anything else that doesn’t concern the actual problem you’re trying to solve.

Maybe there should be a site for collecting single-file libraries like this. But that’s a problem for another day.