Groovy web console

subscribe to the feed Subscribe
to this
site
DSL for String (via #groovywebconsole)
tweet this snippet Tweet
this
script

DSL for String

Published 3 years ago by Serge Rehem with tags string dsl lines size
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
String poem = /
to be 
or 
not to be 
/  

// Using String readLines() method
assert poem.readLines().size() == 4  

// Adding 2 new methods to String
String.metaClass.lines << {-> delegate.readLines() }
String.metaClass.numberOfLines << {-> delegate.readLines().size() }

// Using both
assert poem.lines().size() == 4 
assert poem.numberOfLines() == 4 

// Creating a new DSL for getting the number of lines of a given String
give_me = { it } 
number_of_lines = { it.readLines().size() } 
def please(action) { 
  [the: { what ->    
    [of: { n -> action(what(n)) }]  
  }] 
}

def poemSize = please give_me the number_of_lines of poem
assert poemSize == 4