是否可以使用闭包从值列表中创建一组变量? 问这个的原因是基于(例如)两个三个四个或五个部分的列表创建一些递归功能 这里的代码当然不起作用,但任何指针都会有所帮助。然后
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将自然文本转换为公历日历信息,以便我可以在Google日历中设置事件
答案 0 :(得分: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
答案 1 :(得分:0)
当你使用带有List和“each”的闭包时,groovy循环遍历List中的元素,将值放在列表中的“it”变量中。但是,由于您还想跟踪索引,因此还有一个groovy eachWithIndex,它也传入索引
http://groovy.codehaus.org/GDK+Extensions+to+Object
类似
breaks.eachWithIndex {item, index ->
... code here ...
}