2010-12-06 111 views
0

是否可以使用闭包从值列表中创建一组变量? 询问这样做的原因是基于(比如说)两个三四个或五个部分 当然这里的代码不能正常工作清单上创建一些递归功能,但任何指针将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 

编辑>>

是的,我试图找到收拾这个,这是我在每个循环后做了更巧妙的方式

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] 

,如果我决定到另一个项目添加到列表(我只是这样做)我必须记住其中[I]它是成功地提取它

这是再解析日期/次,然后用jChronic自然文本转换成公历信息,所以我就可以在谷歌日历设置一个事件,工人的部分

+0

我重读了你的问题,我不明白你在做什么。我认为我的答案会对你有所帮助,但如果你能举一个你的手术结果的例子,我会更有帮助。 – hvgotcodes 2010-12-06 15:39:58

回答

1

如何:

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 
+0

Fab ...我失踪的一点是这[[vary] [i]] - 谢谢 – 2010-12-06 16:48:38

0

当你使用带有List和“each”的闭包时,groovy遍历List中的元素,将值放入列表中的“it”变量中。不过,既然你也想保持指数的跟踪,有可能也通过在索引中的常规eachWithIndex

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

所以像

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