Workarounds for Common Issues
Although we have seen that some functionality is simply not portable between Ruby 1.8 and 1.9, there are many more areas in which Ruby 1.9 just does things a little differently or more conveniently. In these cases, we can develop suitable workarounds that allow our code to run on both versions of Ruby. Let’s take a look at a few of these issues and how we can deal with them.
Using Enumerator
In Ruby 1.9, you can get back an Enumerator for
pretty much every method that iterates over a collection:
>> [1,2,3,4].map.with_index { |e,i| e + i }
=> [1, 3, 5, 7]In Ruby 1.8, Enumerator is part of the standard
library instead of core, and isn’t quite as feature-packed. However, we
can still accomplish the same goals by being a bit more verbose:
>> require "enumerator"
=> true
>> [1,2,3,4].enum_for(:each_with_index).map { |e,i| e + i }
=> [1, 3, 5, 7]Because Ruby 1.9’s implementation of Enumerator
is mostly backward-compatible with Ruby 1.8, you can write your code in
this legacy style without fear of breaking anything.
String Iterators
In Ruby 1.8, Strings are
Enumerable, whereas in Ruby 1.9, they are not. Ruby
1.9 provides String#lines, String#each_line, String#each_char, and String#each_byte, all of which are not present
in Ruby 1.8.
The best bet here is to backport the features you need to Ruby
1.8, and avoid treating a String as an
Enumerable sequence of lines. When you need that
functionality, use String#lines followed by whatever
enumerable method you need.
The ...
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