Forum Discussion

jrziggy's avatar
jrziggy
New Contributor
4 months ago

Passing variable as index in property, Groovy

Hi.  I am having trouble getting a property to expand in Groovy using the right index after getting a list of data from a data source. I'm trying to pass the index to the property as a variable in the script but it won't work. The values for the random index looks good in the log, and the property expands on any valid number when using a number for the index.

For example (1), this produces a good result:
result = context.expand( '${DataSourceStationNumber#STATION_NUM::9}')

This example (2) fails even thought the random number variable is good and valid:
result = context.expand( '${DataSourceStationNumber#STATION_NUM::randomIndex}')

result is blank in example 2. Example 1 works with any valid number. 
What's the syntax for this, or is it possibly a type issue in the randomIndex? (E.g., needs to be cast as string?)
Thanks.

  • Hello jrziggy 

    It looks like this is a little trick situation...  you need to expand the 'randomIndex' variable before the whole datasource reference is parameter expanded...

    The context.expand is operating on a string, so just manipulate it a little bit to get your number in there instead of the variable that references it...  be mindful of single quote use versus double quote use below.  Simple parameter replacement occurs when double quotes are used.  This sample just gets that variable replaced before the whole context.expands the full parameter.

    result = context.expand( '${DataSourceStationNumber#STATION_NUM::' + "$randomIndex" + '}' );

    Regards,

    Todd

  • Hello jrziggy 

    It looks like this is a little trick situation...  you need to expand the 'randomIndex' variable before the whole datasource reference is parameter expanded...

    The context.expand is operating on a string, so just manipulate it a little bit to get your number in there instead of the variable that references it...  be mindful of single quote use versus double quote use below.  Simple parameter replacement occurs when double quotes are used.  This sample just gets that variable replaced before the whole context.expands the full parameter.

    result = context.expand( '${DataSourceStationNumber#STATION_NUM::' + "$randomIndex" + '}' );

    Regards,

    Todd

  • jrziggy's avatar
    jrziggy
    New Contributor

    Thanks, Todd!
    That double quote got me!  I had tried that, but only using single quotes on the randomIndex variable and that was my downfall.

    Thanks again!
    Jon