gpt4 book ai didi

ruby - 如何使用 Ruby 中的特定步骤迭代反向范围?

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:40 25 4
gpt4 key购买 nike

我可以这样迭代

(0..10).step(2){|v| puts v}

但是,由于反向范围等于空范围,我不能这样迭代

(10..0).step(2){|v| puts v}

它不会给我带来任何好处。当然,我可以像这样向后迭代

10.downto(0){|v| puts v}

但 downto 方法不允许我设置除默认 1 之外的其他步骤。这是非常基本的东西,所以我想应该有一个内置的方法来做到这一点,我不知道。

最佳答案

你为什么不使用Numeric#step :

来自文档:

Invokes block with the sequence of numbers starting at num, incremented by step (default 1) on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.

irb(main):001:0> 10.step(0, -2) { |i| puts i }1086420

关于ruby - 如何使用 Ruby 中的特定步骤迭代反向范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15715525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com