top | item 41105489

(no title)

jballanc | 1 year 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

discuss

order

cout|1 year ago

This 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.

pizza234|1 year ago

The 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.

Lammy|1 year ago

Relevant documentation link for the uninitiated: 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.”

pooriar|1 year ago

Same 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|1 year ago

flipflop 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.