4 ms·
Nice write-up, but no discussion of Ruby's Range class is complete without at least a mention of the venerable flip-flop! Can you predict the output of the fol
by jballanc 2y ago
Nice write-up, but no discussion of Ruby's Range class is complete without at least a mention of the venerable flip-flop!
Can you predict the output of the following?
(1..20).each do |i|
puts i if i.odd?..i.prime?
end
- cout 2y agoThis is one of the few features of Ruby I've never found a use for, and not fit lack of trying. I thought I remembered Matz once saying it would be removed, But I could be wrong. Maybe someone uses it.
- lmz 2y agoIt's from Awk, probably via Perl. https://www.gnu.org/software/gawk/manual/html_node/Ranges.html https://www.gnu.org/software/gawk/manual/html_node/Ranges.ht...
- pizza234 2y agoThe flip-flop operator is very useful to extract continuous subsets, typically, sections of (multi-line) strings, where the dev defines the delimiters - think of the `=begin` and `=end` keywords. I've personally never used for anything else than strings, but when I do, it's very useful.
- pooriar 2y agoSame as this? (1..20).each do |i| puts i if i.odd? || i.prime? end edit - upon testing, I just realized the parent's code prints 10 & 16, my code does not, so not the same.
- codesnik 2y agoflipflop basically has a hidden boolean variable for state. Btw, while I HAD used it, i still have no idea what's the scope of that state and when it'd reset itself.
- Lammy 2y agoRelevant documentation link for the uninitiated: https://docs.ruby-lang.org/en/master/syntax/control_expressions_rdoc.html#label-Flip-Flop https://docs.ruby-lang.org/en/master/syntax/control_expressi... “The form of the flip-flop is an expression that indicates when the flip-flop turns on, .. (or ...), then an expression that indicates when the flip-flop will turn off. While the flip-flop is on it will continue to evaluate to true, and false when off.”