是否有理由我们无法迭代“反向范围”?在红宝石?

编程入门 行业动态 更新时间:2024-10-22 18:51:08
本文介绍了是否有理由我们无法迭代“反向范围”?在红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试使用范围和每个向后迭代:

I tried to iterate backwards with using a Range and each:

(4..0).each do |i| puts i end ==> 4..0

通过 0..4 写下数字。在另一个范围 r = 4..0 似乎没问题, r.first == 4 , r.last == 0 。

Iteration through 0..4 writes the numbers. On the other Range r = 4..0 seems to be ok, r.first == 4, r.last == 0.

我觉得上面的结构不能产生预期的结果似乎很奇怪。这是什么原因?当这种行为合理时会出现什么情况?

It seems to be strange to me that the construct above does not produce the expected result. What is the a reason for that? What are the situations when this behaviour is reasonable?

推荐答案

范围就是:由开始和结束定义的东西,而不是按其内容。在一般情况下,迭代范围并不真正有意义。例如,考虑如何迭代两个日期产生的范围。你会白天迭代吗?按月?按年?一周?它没有明确定义。 IMO,它允许转发范围这一事实应仅被视为一种便利方法。

A range is just that: something defined by its start and end, not by its contents. "Iterating" over a range doesn't really make sense in a general case. Consider, for example, how you would "iterate" over the range produced by two dates. Would you iterate by day? by month? by year? by week? It's not well-defined. IMO, the fact that it's allowed for forward ranges should be viewed as a convenience method only.

如果你想在这样的范围内向后迭代,你可以随时使用 downto :

If you want to iterate backwards over a range like that, you can always use downto:

$ r = 10..6 => 10..6 $ (r.first).downto(r.last).each { |i| puts i } 10 9 8 7 6

以下是 更多想法 来自其他人,为什么很难同时允许迭代并始终​​处理反向范围。

Here are some more thoughts from others on why it's tough to both allow iteration and consistently deal with reverse-ranges.

更多推荐

是否有理由我们无法迭代“反向范围”?在红宝石?

本文发布于:2023-11-29 08:33:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:红宝石   有理由   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!