是否有理由我们无法迭代“反向范围”?在红宝石? [英] Is there a reason that we cannot iterate on "reverse Range" in ruby?

查看:87
本文介绍了是否有理由我们无法迭代“反向范围”?在红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于是否有理由我们无法迭代“反向范围”?在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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