john renfrew
john renfrew

Reputation: 413

groovy closure instantiate variables

is it possible to create a set of variables from a list of values using a closure?? the reason for asking this is to create some recursive functionality based on a list of (say) two three four or five parts The code here of course doesn't work but any pointers would be helpful.then

def longthing = 'A for B with C in D on E'
//eg shopping for 30 mins with Fiona in Birmingham on Friday at 15:00
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']

i = 0
line = place = with = event = ""
breaks.each{
shortline = longthing.split(breaks[i])
longthing= shortline[0]
//this is the line which obviously will not work
${vary[i]} = shortline[1]
rez[i] = shortline[1]
i++
 }
return place + "; " + with + "; " + event
// looking for answer of D; C; B

EDIT>>

Yes I am trying to find a groovier way to clean up this, which i have to do after the each loop

len = rez[3].trim()
if(len.contains("all")){
len = "all"
} else if (len.contains(" ")){
len = len.substring(0, len.indexOf(" ")+2 )
}
len = len.replaceAll(" ", "")
with = rez[2].trim()
place = rez[1].trim()
when = rez[0].trim()
event = shortline[0]

and if I decide to add another item to the list (which I just did) I have to remember which [i] it is to extract it successfully

This is the worker part for then parsing dates/times to then use jChronic to convert natural text into Gregorian Calendar info so I can then set an event in a Google Calendar

Upvotes: 0

Views: 435

Answers (2)

btiernay
btiernay

Reputation: 8129

How about:

def longthing = 'A for B with C in D on E'
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
rez = []
line = place = with = event = ""

breaks.eachWithIndex{ b, i ->
  shortline = longthing.split(b)
  longthing = shortline[0]
  this[vary[i]] = shortline[1]
  rez[i] = shortline[1]
}
return place + "; " + with + "; " + event

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120308

when you use a closure with a List and "each", groovy loops over the element in the List, putting the value in the list in the "it" variable. However, since you also want to keep track of the index, there is a groovy eachWithIndex that also passes in the index

http://groovy.codehaus.org/GDK+Extensions+to+Object

so something like

breaks.eachWithIndex {item, index ->
   ... code here ...
}

Upvotes: 0

Related Questions