0 Replies - 1792 Views - Last Post: 15 September 2014 - 10:35 PM

#1 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1453
  • View blog
  • Posts: 3,633
  • Joined: 28-November 09

Flipflop HTML Yanking

Posted 15 September 2014 - 10:35 PM

IO.readlines('test.html')
  .flat_map(&:split)
  .select { |word|
    true if word =~ %r{<strong>} .. word =~ %r{</strong>}
  }

# => ["<strong>multiple</strong>","<strong>strong</strong>"]

# test.html
#
# <html>
#   <body>
#     <h1>Foobar</h1>
# 
#     <p>Let's see how this works</p>
# 
#     <p>With <strong>multiple</strong> seperated <strong>strong</strong> words</p>
#   </body>
# </html>



But that's a range! How does that even work? A lesser known operator known as the Flip Flop. When used in a conditional (reason for the true if part) it treats them like a flip flop.

So what is a flip flop? Think of it as an anonymous flag for getting a range of input starting with a beginning match and ending with an ending match:
str = "a BEGIN bcd END efg"
str.split.select { |word| true if word.match(/BEGIN/)..word.match(/END/) }

# How does Ruby process this?
# words are [a, BEGIN, bcd, END, efg]
#
# Start the iteration:
# 1. a does not match BEGIN
# 2. BEGIN matches BEGIN, anonymous flag set to true
# 3. bcd does not match END
# 4. END matches END, anonymous flag set to false
# 5. efg does not match BEGIN
#
# Returns [BEGIN, bcd, END]



Handy, but definitely one not to abuse.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1