是否有我们不能迭代“反向范围"的原因?在红宝石? [英] Is there a reason that we cannot iterate on "reverse Range" in ruby?

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

问题描述

我尝试使用 Range 和 each 向后迭代:

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天全站免登陆