简体   繁体   English

常规闭包实例化变量

[英]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 如果我决定将另一个项目添加到列表中(我刚刚做了),我必须记住要成功提取出哪个[i]

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 这是工作部件,用于解析日期/时间,然后使用jChronic将自然文本转换为公历日历信息,因此我可以在Google日历中设置事件

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

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. 当使用带有List和“ each”的闭包时,groovy循环遍历List中的元素,将列表中的值放在“ it”变量中。 However, since you also want to keep track of the index, there is a groovy eachWithIndex that also passes in the index 但是,由于您还想跟踪索引,因此在索引中还传递了一个俗套的eachWithIndex

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

so something like 所以像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM