From: Michael Ulm Date: 2007-10-25T15:40:00+09:00 Subject: Re: Intervals in Ruby 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). If there is only one kind of range to be supported (which I understand to be in sync with the Python philosophy), I agree that half-open intervals are the way to go. > > 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 The two different ranges are nice-to-have, because sometimes the closed interval is the right thing to use. I'd have exchanged the syntax 'though. Having said that, I have never had a problem distinguishing the two. > > 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 --snip-- This is not really a range, but the Ruby Way of looping; it is what made me fall in love with Ruby in the first place. For me, it is one the most beautiful aspects of any programming language that I know. Best regards, Michael