hn.today

C-like bit flags in Ruby

citizen428.net10 points0 comments
Screenshot of C-like bit flags in Ruby

The piece presents a compact way to define C-style bit flags in Ruby without adding a dependency. Calling `BitFlags.for` with names such as `:execute`, `:write`, and `:read` creates a flag set in which each name corresponds to a distinct power of two. The resulting constants can be combined with Ruby’s bitwise OR, and generated predicate methods - such as `Permission.read?` - test whether a flag is present in a combined value. The examples build an execute-and-read permission and check that read and execute are enabled while write is not.

The implementation also provides `parse`, which turns an integer flag value into a form usable in Ruby’s pattern matching. That lets callers branch on cases such as no flags, all flags, an exact combination, the presence of read, or one of two alternatives. The included tests demonstrate these cases with values from zero through seven. The code is released under the CC0 public-domain dedication and can be downloaded and tested directly with Ruby. The author argues against packaging it as a gem because the feature is small and understandable enough to copy and adapt; avoiding a dependency also sidesteps version constraints and supply-chain concerns. The piece additionally suggests that a collection of useful single-file libraries could be worthwhile.

Read on citizen428.net0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

Solid 2.0

Solid 2.0

Solid 2.0 is now stable, five years after version 1.0, with a smaller API and diagnostics designed for AI agents. Its reactive graph now handles asynchronous computations, while built-in server functions support RPC calls and persistent Server-Sent Events connections. (solidjs.com)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.