Re: Using variables in an embedded Groovy script

Jochen Wiedmann <[email protected]>
Newsgroups gmane.comp.lang.groovy.user
Message-ID <pony-c02b2dea-bbbd-4fa5-ad8e-fd282df73858-users@groovy.apache.org>
Thank you, using toString() works perfectly.


On 2023/09/27 12:28:24 Paul King wrote:
> For a GString, the strings property contains the static parts and the
> values property contains the expressions.
> 
> def name = 'world'
> def gstr = "Hello, $name!"
> assert gstr.strings[0] == 'Hello, '
> assert gstr.strings[1] == '!'
> assert gstr.values[0] == 'world'
> assert gstr.toString() == 'Hello, world!'
> 
> Your code is just concatenating the static parts. You can just use the
> toString() value or in general if you wanted to concatenate by hand
> strings[0] + values[0] + strings[1] + values[1] + strings[2] +
> values[2] + strings[3] and so forth for as many terms as needed.
> 
> Another example:
> 
> def gstr = "foo ${1+1} bar ${'w' * 3} baz"
> assert gstr.strings == ['foo ', ' bar ', ' baz']
> assert gstr.values == [2, 'www']
> assert gstr.toString() == 'foo 2 bar www baz'
> 
> On Wed, Sep 27, 2023 at 9:45 PM Jochen Wiedmann <[email protected]> wrote:
> >
> >
> > Hi, Paul,
> >
> > could you, please, explain what you mean? I really have no idea, what you mean.
> >
> > Thanks,
> >
> > Jochen
> >
> >
> > On 2023/09/25 15:07:28 Paul King wrote:
> > > You'd need to interleave the values from the GString.
> > >
> > > On Tue, Sep 26, 2023 at 12:43 AM Jochen Wiedmann
> > > <[email protected]> wrote:
> > > >
> > > > Hi,
> > > >
> > > > can anyone advise me, what is wrong with the following code: I'd
> > > > expect it to write out the word "Okay". Instead, it throws the
> > > > exception "Unexpected result: Hello, !"
> > > >
> > > > final String scriptStr = "return \"Hello, $name!\";";
> > > > final GroovyShell gs = new GroovyShell();
> > > > final Script script = gs.parse(new StringReader(scriptStr));
> > > >
> > > > final Binding binding = new Binding();
> > > > binding.setProperty("name", "world");
> > > > script.setBinding(binding);
> > > >
> > > > final GStringImpl gsi = (GStringImpl) script.run();
> > > > final String[] gsArray = gsi.getStrings();
> > > > final String result;
> > > >
> > > > if (gsArray == null || gsArray.length == 0) {
> > > >     result = null;
> > > > } else {
> > > >     result = String.join("", gsArray);
> > > > }
> > > >
> > > > if (!"Hello, world!".equals(result)) {
> > > >     throw new IllegalStateException("Unexpected result: " + result);
> > > > }
> > > > System.out.println("Okay.");
> > > >
> > > >
> > > >
> > > > --
> > > > The woman was born in a full-blown thunderstorm. She probably told it
> > > > to be quiet. It probably did. (Robert Jordan, Winter's heart)
> > >
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.