When would a Ruby flip-flop be useful?

后端 未结 3 1593
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 00:30

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 00:59

    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.

提交回复
热议问题