I’ve been reading through the latest version of the pick-axe book, and I came across a really interesting construct of Ruby that I’ve never seen in another language – Range Conditions.
[Range conditions] turn on when the condition in the first part of the range becomes true, and turn off when the condition in the second part becomes true.
If that seems confusing the first time you read it, you’d be in the same boat as me. Let’s use an example from the book:
while line = gets puts line if line =~ /start/ .. line =~ /end/ end
So in this example puts will start to execute once the regex /start/ matches.
From that point on, puts will continue to execute until the regex /end/ is matched, at that point puts will stop functioning. Here’s an example of that output:
> a => > start => start > b => b > end => end > c =>
The thing that I find very interesting about this construct is how much code it replaces, the equivalent code would look like this:
while line = gets @output = true if line =~ /start/ puts line if @output @output = false if line =~ /end/ end
Now all I have to do is find a case where using this code makes sense! :P
