From: Just Another Victim of the Ambient Morality Date: 2007-10-25T16:30:12+09:00 Subject: Re: Intervals in Ruby "Steven D'Aprano" wrote in message news:13hvt65e4d1vd0b@corp.supernews.com... > Howdy, > > 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? They're obviously not used a lot but they can be useful. They're really for times when you know the start and end points of indexing, rather than the start and length of indexing. My girlfriend in highschool (who was wonderfully nerdy) was well aware of off-by-one errors while not being a computer programmer (she was into math and physics and went into engineering) because of problems like asking how many days someone has stayed somewhere if they arrived on the 5'th and left on the 16'th. The naive answer, of course, is 16 - 5 but, upon closer inspection, it would actually be 16 - 5 + 1. Apparently, this pattern has happened to her more than once 'cause it came up (somehow) and she brought alot of attention to this fact, so much so that I still remember this and am relaying it to all of you... So, in Python, if you wanted to access the fifth to sixteenth element in an array, you'd need to do something like this: for i in range(5, 16 + 1): array[i] # do something with this... Some people might be tempted to just stick 17 in there but I wouldn't...