[译] Ruby 2.6 增加无穷范围

栏目: Ruby · 发布时间: 7年前

内容简介:本博客系列翻译自 Bigbinary 的Ruby 2.6 系列, 已得到作者允许。Ruby 2.6.0-preview2 现已发布。在Ruby 2.6 之前,如果你想要使用带上索引(index)的无限循环,我们得用 Float::INFINITY 然后用 #upto 方法 或者实现一个Range 实例,或者用 Numeric#step 方法。或者

本博客系列翻译自 Bigbinary 的 Ruby 2.6 系列, 已得到作者允许。Ruby 2.6.0-preview2 现已发布。

在Ruby 2.6 之前,如果你想要使用带上索引(index)的无限循环,我们得用 Float::INFINITY 然后用 #upto 方法 或者实现一个Range 实例,或者用 Numeric#step 方法。

Ruby 2.5.0

irb> (1..Float::INFINITY).each do |n|
irb*   # logic goes here
irb> end
复制代码

或者

irb> 1.step.each do |n|
irb*   # logic goes here
irb> end
复制代码

Ruby 2.6.0

Ruby 2.6 让Range 中第二个参数变成可选的,让无限循环更具有可读性(并没有)。Ruby 让第二个参数可以是nil,所以 (0..) 和 (0..nil) 在Ruby 2.6 是等价的了。

irb> (0..).each do |n|
irb*   # logic goes here
irb> end
复制代码
irb> (0..nil).size
=> Infinity
irb> (0..).size
=> Infinity
复制代码

如果是Ruby 2.5, (0..nil) 这样会抛出 ArgumentError。

irb> (0..nil)
ArgumentError (bad value for range)
复制代码

这里是相关的 commit 和讨论

原文地址


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Clean Code

Clean Code

Robert C. Martin / Prentice Hall / 2008-8-11 / USD 49.99

Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code......一起来看看 《Clean Code》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具