Why does 6m.map work in ruby ​​1.8.7, but not 1.8.6

The following code snippet works fine in 1.8.7 on Mac OS X, but not in 1.8.6 on Ubuntu. What for? Is there any workaround?

Works in 1.8.7:

$ ruby --version ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0] ltredgate15:eegl leem$ irb >> 6.times.map {'foo'} => ["foo", "foo", "foo", "foo", "foo", "foo"] >> 

But not in 1.8.6:

 # ruby --version ruby 1.8.6 (2008-08-11 patchlevel 287) [i686-linux] Ruby Enterprise Edition 20090610 # irb irb(main):001:0> 6.times.map {'foo'} LocalJumpError: no block given from (irb):1:in `times' from (irb):1 irb(main):002:0> 

Why is there a difference? What is the workaround for 1.8.6?

+7
ruby ruby-enterprise-edition
source share
4 answers

In 1.8.7+, iterator methods, such as times , return an enumerator if they are called without a block. In 1.8.6 you should do

 require 'enumerator' 6.enum_for(:times).map {...} 

Or for this particular use case you can just do (0...6).map {...}

+16
source share

In Ruby 1.9, the library was modified so that iteration returned an Enumerator object if they were called without a block. A number of other language features were also modified, and it was widely known that compatibility would be compromised between Ruby 1.8.x and Ruby 1.9 in the interest of improving the language as a whole. Most people did not find this too sad.

The Ruby development team decided that Ruby 1.8.7 should be a transition release by adding some of the library features that Ruby 1.9 introduced. They took a lot of criticism for the decision, and many users of corporate Ruby stayed (and many of them still remain) with Rails on Ruby 1.8.6 because they feel that the changes made to 1.8.7 are too big and too risky. But, nevertheless, 1.8.7 remains, and iteration functions are returned. Enumerators are one of the features that have been included.

It is this migration function that you see in 1.8.7, which is missing in 1.8.6.

Answer

sepp2k provides a good workaround. I have nothing to add to this.

+6
source share

Since 1.8.6 # is multiplied by this block, and 1.8.7 returns an Enumerator object, which you can save and implement Enumerable.

+1
source share

Ruby 1.8.7 introduces a lot of changes . If you want to use them in Ruby 1.8.6, just

 require 'backports' 

What is it. This gives you many methods 1.9.1 and upcoming 1.9.2, although it is possible to require 'backports/1.8.7' only for 1.8.7 changes, or even only for the required backports, for example. require 'backports/1.8.7/integer/times'

+1
source share

All Articles