From: "ara.t.howard" Date: 2007-10-26T05:53:34+09:00 Subject: Re: Intervals in Ruby On Oct 24, 2007, at 7:45 PM, Steven D'Aprano wrote: > 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? i use both frequently. '...' is always leads to shorter code when complex iterations are done and, of course, lead to fewer off by one errors since ruby arrays are zero index based. > > How useful are the closed interval forms? Do you find yourself > making off- > by-one errors or needing to increment/decrement variables by one? no. but i've fixed alot of code that has. > > 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? > in my experience open intervals, in c, fortran, c++ and idl often lead to off by one errors but, that being said, i think it's less in fortran because it uses '1' based arrays. also, anyone whose has coded C has probably found 'off, length' to be less error prone and open intervals lend themselves more easily to that notion. cheers. a @ http://codeforpeople.com/ -- we can deny everything, except that we have the possibility of being better. simply reflect on that. h.h. the 14th dalai lama