tags:

views:

312

answers:

1

I think I understand how a flip-flop works thanks to this tutorial, but the example there is contrived just for teaching. Can anyone give an example of how you have actually used or would use a flip-flop?

Edit: I'm looking for a real-world application, not just another demonstration. What problems can this tool solve?

+4  A: 

Here's an example (taken from a rubycentral.com article) where you print out only certain lines from a file:

file = File.open("ordinal")
while file.gets
    print if ($_ =~ /third/) .. ($_ =~ /fifth/)
end

This assumes that you have a file with the following contents:

first
second
third
fourth
fifth
sixth

The program will only print out:

third
fourth
fifth

The idea is that it the value is true until the left-hand event happens, and then stays true until the right-hand event happens. If used properly this can be a nice piece of syntactic sugar, but you need to be careful to make things readable.

Edit: fixed code that rampion found objectionable.

Reference:

James Thompson
-1: untested code. What do you think this is, perl? you need `print if ($_ =~ /third/) .. ($_ =~ /fifth/)` (I know it's not your code, but there's no need to continue spreading code that uses deprecated features).
rampion
What is the actual use for this? When might I need to print the 3rd through 5th lines from a file (enough times to make it worth coding)?
kajaco
Forget about 3 and 5. It's about extracting a section of the file delimited by a begin tag and an end tag. I hope you see better why that's a real world example.. Now the equivalent non-flip-flop version would involve adding variable for the state, more if statements: just more complex code.
inger
Wow, now i'm seeing my ruby's object orientated nature is so powerful.. using ranges in ways like this. Just amazing!
Codygman
… this isn’t a range. You completely misunderstood the flip-flop operator. It’s the same piece of syntax, that happens to mean a completely different thing in this context. (Nobody ever said Ruby’s syntax was simple: http://j.mp/cu0eFz - and that’s extremely incomplete!)
elliottcable