Andreas Haller
10/25/2007 3:09:00 AM
> My question is: how useful are all these different mechanisms? Do you
> find that having two operators .. and ... is a blessing, or a curse
> because you can never remember which is which?
Hi
i think it makes perfect sense to have those two options and with
such a similar syntax. I had to think a second everytime to remember
which is which, but i got used to it now. (Although it does not make
much sense to me that three dots mean "less" than two dots.)
> [...]. range() always results in a half-open interval:
> range(1, 5) => 1, 2, 3, 4
I had to look up the terms "half-open" and "half-closed". http://
en.wikipedia.org/wiki/Interval_(mathematics) says that an half-open
interval (2,4] excludes 2, but includes 4. So in Python that would be
half-closed intervals by default (right?), ikewise in Ruby.
I did not know upto() and downto() Uups.
Together with n.times they are just nice to have and you can use the
one message that would be the most expressive, depending what you
want to write.
What i find strage about ranges is that:
(0..3).to_a # => [0, 1, 2, 3]
but
(3..0).to_a # => []
Regarding the "off-by-one" question, i dont really know.
andreas
Am 25.10.2007 um 03:45 schrieb Steven D'Aprano:
> Howdy,
>
> I'm not a Ruby developer *at all*, I use Python, but this is not
> flame-
> bait. I'm interested in how Ruby folks find using intervals.
>
> In Python, we deal with integer ranges virtually exclusively with the
> range() function. range() always results in a half-open interval:
>
> range(5) => 0, 1, 2, 3, 4
> range(1, 5) => 1, 2, 3, 4
> range(4, -1, -1) => 4, 3, 2, 1, 0
>
> The start argument is always included, the end argument is never
> included, and there is an optional step size (defaults to 1).
>
>
> I understand that in Ruby you have quite a few choices, some of
> which are
> half-open like Python, some of which are closed:
>
> 0..5 => 0, 1, 2, 3, 4, 5
> 0...5 => 0, 1, 2, 3, 4
>
> 5.downto(1) => 5, 4, 3, 2, 1
> 1.upto(5) => 1, 2, 3, 4, 5
> 5.times() => 0, 1, 2, 3, 4
> 5.step(11, 3) => 5, 8, 11
>
> and the Range.new method.
>
> My question is: how useful are all these different mechanisms? Do you
> find that having two operators .. and ... is a blessing, or a curse
> because you can never remember which is which?
>
> How useful are the closed interval forms? Do you find yourself
> making off-
> by-one errors or needing to increment/decrement variables by one?
>
> e.g. do you often need to write things like:
>
> start.step(end + 1, increment){| i | block }
> start.step(end - 1, increment){| i | block }
>
> Writing in Python, I almost never need to "shift the fence-posts",
> so to
> speak. E.g. I virtually never need to write something like:
>
> range(start, end+1)
>
> to avoid an off-by-one error. When I used to program in Pascal (which
> exclusively uses closed intervals) I used to need to do it all the
> time.
> What's the Ruby experience?
>
>
>
> Thank you,
>
>
>
>
> --
> Steven
>