为什么 6.times.map 在 ruby​​ 1.8.7 中有效,但在 1.8.6 中无效 [英] Why does 6.times.map work in ruby 1.8.7 but not 1.8.6

查看:36
本文介绍了为什么 6.times.map 在 ruby​​ 1.8.7 中有效,但在 1.8.6 中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码片段在 Mac OS X 上的 1.8.7 中运行良好,但在 Ubuntu 上的 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?

适用于 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"]
>>

但不是在 1.8.6:

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> 

为什么会有区别?1.8.6 的解决方法是什么?

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

推荐答案

在 1.8.7+ 迭代器方法中,例如 times 如果在没有块的情况下调用它们,则返回一个枚举器.在 1.8.6 你必须做的

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 {...}

或者对于这个特定用例,您可以简单地执行 (0...6).map {...}

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

这篇关于为什么 6.times.map 在 ruby​​ 1.8.7 中有效,但在 1.8.6 中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆