views:

30

answers:

1

I am unable to use the fabulous tr() at the moment as I can only use Groovy 1.7.1 and wanted to know if there is an elegant way of going backwards and forwards between string and number encoded with Base32, but with the values A to Z then 2 to 7, rather than 0 to 9 then A to V.

This is to remove customer error in typing in a human readable code by not using zero or one.

I can think of 72 Regex expressions that would enable this, but that seems like overkill when

tr( 'A-Z2-7', 0-9A-V')

is SO much easier

+4  A: 

The beauty of Groovy is its dynamic nature. If you need the feature, but it's not there, add it! Somewhere in a convenient entry point to your application, or in a static block in the class that needs it, add the code lifted straight from the 1.7.3+ sources:

String.metaClass.'static'.tr = { String text, String source, String replacement ->
    if (!text || !source) { return text }
    source = expandHyphen(source)
    replacement = expandHyphen(replacement)

    // padding replacement with a last character, if necessary
    replacement = replacement.padRight(source.size(), replacement[replacement.size() - 1])

    return text.collect { original ->
        if (source.contains(original)) {
            replacement[source.lastIndexOf(original)]
        } else {
            original
        }
    }.join()
}


String.metaClass.'static'.expandHyphen = { String text ->
    if (!text.contains('-')) { return text }
    return text.replaceAll(/(.)-(.)/, { all, begin, end -> (begin..end).join() })
}

String.metaClass.tr = { String source, String replacement ->
    String.tr(delegate, source, replacement)
}

The nice thing about this is whenever you can upgrade to 1.7.3, you can just remove this meta-magic and you won't need to change your other sources.

Brian M. Carr
Delphyne, that demonstrates the beauty of why more heads are better than one. Am still quite new to Groovy, which I am using inside Filemaker, and so was just looking at this down a single avenue and of course this just works a treat.I need to become more au fait with docs and source code..MANY thanks for your input.
john renfrew
Where do I have to go to get a look at the source so I can start extending my learning??
john renfrew
The sources are available for download along side the binaries [1]. The trick is that it can be non-obvious to figure out where things are implemented. In the code I posted above, the static 'tr' and 'expandHyphen' methods exist in a class called StringUtils, while the instance 'tr' method exists in DefaultGroovyMethods.[1] http://groovy.codehaus.org/Download
Brian M. Carr