繁体   English   中英

常规闭包实例化变量

[英]groovy closure instantiate variables

有可能使用闭包从值列表中创建一组变量吗? 要求这样做的原因是基于(例如)两个,三个,四个或五个部分的列表创建一些递归功能。这里的代码当然不起作用,但是任何指针都会有所帮助。

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日历中设置事件

怎么样:

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

当使用带有List和“ each”的闭包时,groovy循环遍历List中的元素,将列表中的值放在“ it”变量中。 但是,由于您还想跟踪索引,因此在索引中还传递了一个俗套的eachWithIndex

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

所以像

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

暂无
暂无

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

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