我尝试使用范围和每个向后迭代:
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.
更多推荐
是否有理由我们无法迭代“反向范围”?在红宝石?
发布评论