Nonportable Features in Ruby 1.9
There are some features in Ruby 1.9 that you simply cannot backport to 1.8 without modifying the interpreter itself. Here we’ll talk about just a few of the more obvious ones, to serve as a reminder of what to avoid if you plan to have your code run on both versions of Ruby. In no particular order, here’s a fun list of things that’ll cause a backport to grind to a halt if you’re not careful.
Pseudo-Keyword Hash Syntax
Ruby 1.9 adds a cool feature that lets you write things like:
foo(a: 1, b: 2)
But on Ruby 1.8, we’re stuck using the old key => value syntax:
foo(:a => 1, :b => 2)
Multisplat Arguments
Ruby 1.9.1 offers a downright insane amount of ways to process arguments to methods. But even the more simple ones, such as multiple splats in an argument list, are not backward compatible. Here’s an example of something you can do on Ruby 1.9 that you can’t do on Ruby 1.8, which is something to be avoided in backward-compatible code:
def add(a,b,c,d,e) a + b + c + d + e end add(*[1,2], 3, *[4,5]) #=> 15
The closest thing we can get to this on Ruby 1.8 would be something like this:
add(*[[1,2], 3, [4,5]].flatten) #=> 15
Of course, this isn’t nearly as appealing. It doesn’t even handle the same edge cases that Ruby 1.9 does, as this would not work with any array arguments that are meant to be kept as an array. So it’s best to just not rely on this kind of interface in code that needs to run on both 1.8 and 1.9.
Block-Local Variables
On Ruby 1.9, block variables will ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access