Use beautiful binary literals in Ruby

I don't know about you, but even after all these years of UNIX I still have some trouble interpreting octal permissions in my head. In this episode, you'll learn about a special form of the integer literal syntax that can take the math out of bitfields.

You probably already know a lot of the literal syntax in Ruby. Stuff like literal integers, floating point numbers, and strings.

42
3.14159
"foo"

You probably also know that like many languages, Ruby has a literal syntax for hexidecimal and octal numbers:

0x7FFF # => 32767
0755   # => 493

Octal numbers are useful for things like specifying unix file permissions.

require 'fileutils'
include FileUtils

chmod 0755, 'somefile'

Ruby also supports a slightly less common type of integer literal: binary literals. I don't know about you, but even after all these years of UNIX I still have some trouble translating octal numbers into permissions, and vice-versa, in my head. This is one place binary literals can come in handy.

Let's take a look at the previous example, only using a binary literal this time. First, we'll start with a reminder of the order of permissions bits. From left to write, we have permissions for user, group, and other.

# U  G  O
# rwxrwxrwx

Now underneath that, we'll spell out our permission mask as a binary literal.

# U  G  O
# rwxrwxrwx
0b111101101

Just to check, we'll translate that to octal form.

perms = 0b111101101
perms.to_s(8) # => "755"

Now with our permissions mask in hand, we can set permissions, confident that we've set the desired bits.

chmod perms, 'somefile'

And that's it for today. Happy hacking!