Caffeine-Powered Life

Ruby Is Not C# So Don't Code That Way

I’ve recently been checking out Albacore. It’s a build system written in Ruby. I’ve gotten pretty good at MSBuild in the last year, but even the best MSBuild script is still really ugly. Albacore certainly looks promising, and I would love the opportunity to secretly introduce some Ruby sauce into my professional work life.


COMPILE_TARGET = ENV['config'].nil? ? "debug" : ENV['config']

If you were writing that exact same line in C#, only changing the syntax to make it C# appropriate, you’d write this instead.


static string COMPILE_TARGET = ENV["config"] == null ? "debug" : ENV["config"]

C# can take a shortcut with the null coalescing operator, though. So you’d shorten that line above to something like this.


static string COMPILE_TARGET = ENV["config"] ?? "debug"

But Ruby can null coalesce, too, but it doesn’t have a coalescing operator. Instead, you’ll use an “or” || operator. It’s important to remember that every statement returns something in Ruby. And, there are two things that return false in Ruby: false and nil. You should remember that from when we went through the Ruby koans. Everything else is true. This next Ruby line is exactly the same as that last C# line.


COMPILE_TARGET = ENV['config'] || 'debug'

If ENV['config'] has a value, then that value will be assigned to COMPILE_DEBUG. If it is nil, then the right side of the || operator will kick in and assign ‘debug’. That’s a lot fewer keystrokes and it does the exact same thing. Want to learn even more Ruby tricks that can save you a lot of time and keystrokes? Check out The Ruby Programming Language by David Flanagan and Yukihiro Matsumoto. It’s the best Ruby book out there for getting into the gritty of the language.

Comments