Ruby Flip Flop or Range Operators

Ruby's flip flop operator(s) take the exact same syntax as ranges do. For example the following are ranges:

1..10
5..10
10...100
(10...100)

The difference with flip flops is that both the left hand and right hand operands must be boolean expressions, for example observe the following:

items = %w[ just some items within this list ]
puts items.collect {|item| item if (item.length == 4)..(item.length > 4)}

which results in the following. At first you might be wondering, what the hell is this really doing!! well first we have our array of items, we are going to print each item which was collected. The item is returned (collected) when the item length is 4, or the last item length was 4, this is a result of the flip flop mechanism storing the bool of its last operation. The right hand side of our flip flop switches its state to false when an items length is larger than 4.

Still confused? take a look at our output, items is larger than 4 however it is displayed since the last item had a length of four, however we get nil after that due to the flip flop switching its state once it operates on the 5 letter word 'items'.

just
some
items
nil
this
list

Parsing Script With Ruby

The example below was the first implementation I could think of which displays the flip flop operator in a useful manor. Using the flip flop prevents us from needing to store a bool which would indicate that we are currently 'within' a comment.

code = <<-CODE
  /**
   * Some comments
   * longer comments here that we can parse.
   *
   * Wahoo
   */
   function subroutine() {
    
   }
  
   /* some more comments */
  
   /**
    * Another comment.
    */
    function something() {
     
    }
CODE

comments = code.collect { |line| line if (line =~ /^[\s]*\/\*/)..(line =~ /^[\s]*\*\//) }.join 
puts comments

outputs as:

  /**
   * Some comments
   * longer comments here that we can parse.
   *
   * Wahoo
   */
  
   /* some more comments */
  
   /**
    * Another comment.
    */