Groovy web console

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

Characters

Published 3 months ago by Donal
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
public class Characters {
    private String string
    
    public Characters(Object value) {
        string = value.toString()
    }
    
    def propertyMissing(String name) {
        
        if (name ==~ /c[1-9]+/) {
            def charIndex = name[1..-1].toInteger() - 1
            return string[charIndex]
        }        
        throw new MissingPropertyException(name, Characters)
    }
}

// test valid property calls
def c = new Characters('1234567')

assert c.c2 == '2'
assert c.c6 == '6'

// test invalid property calls
try {
  c.c99
  assert false, 'this line should not be reached'

} catch (StringIndexOutOfBoundsException ex) {
  println "Expected ${ex.getClass().simpleName}"
}

try {
  c.foo
  assert false, 'this line should not be reached'

} catch (MissingPropertyException ex) {
  println "Expected ${ex.getClass().simpleName}"
}