[译] Ruby 2.6 增加无穷范围

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

内容简介:本博客系列翻译自 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 和讨论

原文地址


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

查看所有标签

猜你喜欢:

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

Flexible Pattern Matching in Strings

Flexible Pattern Matching in Strings

Gonzalo Navarro、Mathieu Raffinot / Cambridge University Press / 2007-7-30 / USD 64.99

String matching problems range from the relatively simple task of searching a single text for a string of characters to searching a database for approximate occurrences of a complex pattern. Recent ye......一起来看看 《Flexible Pattern Matching in Strings》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具