2010-12-06 113 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 ... 
}