..
or flip-flop is inherited from Perl which got it from AWK and sed in *nix. It's very powerful, but in your particular use it's fairly obscure and not a good choice for the logic you want, especially in Ruby. Instead use:
(1..10).each {|x| puts x if (3..5) === x }
Which outputs:
3
4
5
That said, it's extremely powerful when you need to extract a range of lines from a file:
File.foreach('/usr/share/dict/propernames') { |li| puts li if ($. == 5 .. $. == 7) }
Which outputs:
Agatha
Ahmed
Ahmet
Perl allows an even more-terse expression using only the line numbers of the currently read line (AKA $.
) but Ruby doesn't support that.
There's also the option of using regular expressions, which behave similarly as the previous comparison:
File.foreach('/usr/share/dict/propernames') { |li| puts li if (li[/^Wa/] .. li[/^We/]) }
Which outputs:
Wade
Walt
Walter
Warren
Wayne
Wendell
Because regex work, it's possible to create a complex pattern to retrieve lines from a file based on matches. As the first, then the second pattern trigger, lines are captured. If, later in the file, another line triggers the first pattern, capturing will again occur until the second pattern matches. It's wonderfully powerful:
File.foreach('/usr/share/dict/propernames') { |li| puts li if (
li[/^Am/] .. li[/^An/] or
li[/^Wa/] .. li[/^We/]
)
}
Which outputs:
Amanda
Amarth
Amedeo
Ami
Amigo
Amir
Amos
Amy
Anatole
Wade
Walt
Walter
Warren
Wayne
Wendell
Or alternately, for our obscure-code speaking friends:
File.foreach('/usr/share/dict/propernames') { |li| puts li if (li[/^(?:Am|Wa)/] .. li[/^(?:An|We)/]) }
and continue to be true until x == 5
– KilkennyDifference between .. and ... in boolean ranges
. Read this..Ranges in Boolean Expressions
also. – Ambrosex==3..x==5
vs.(x == 3) .. (x == 5)
. The flop-flop isn't widely known and people stumbling upon it will find it easier to pick apart what's happening. – Ron