C-like bit flags in Ruby

2026-11-11 - 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