Search code examples
rubyruby-enterprise-edition

Why does 6.times.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. Why? Is there a 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's the workaround for 1.8.6?


Solution

  • In 1.8.7+ iterator methods like times return an enumerator if they are called without a block. In 1.8.6 you have to do

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

    Or for this specific use case you could simply do (0...6).map {...}