2013-01-07 44 views
0

我想迭代一個數組,修改其元素基於一個標準,並希望在每個元素之後插入另一個元素,除了最後一個元素之外。什麼是最通俗的Ruby方式呢?迭代數組,修改並插入其他元素

def transform(input) 
    words = input.split 
    words.collect {|w| 
    if w == "case1" 
     "add that" 
    else 
     "add these" + w 
    end 
    # plus insert "x" after every element, but not after the last 
    } 
end 

實施例:

transform("Hello case1 world!") => ["add theseHello", "x", "add that", "x", "add theseworld!"] 
+0

我可能會創建一個新的集合。 –

+0

與往常一樣,樣本輸入和樣本輸出是*必需的。*在英語中很容易模糊。例如,在每個*元素之後是否有「x」?真?因爲你的意思是,「只有在每增加一個新元素之後」。原始元素是否保留? – DigitalRoss

+0

@DigitalRoss你是對的,我的壞!感謝您通過map {...}指出 – Erandir

回答

0

製作大約期望的輸出一些假設,和編輯工作:

def transform(input) 
    input.split.inject([]) do |ar, w| 
    ar << (w == "case1" ? "add that" : "add these" + w) << "x" 
    end[0..-2] 
end 

p transform("Hello case1 world!") 

#=> ["add theseHello", "x", "add that", "x", "add theseworld!"] 
+0

迄今爲止看起來不錯,但我想結果作爲一個數組而不是一個字符串:[「add」,「」,「these」,「」...] – Erandir

+0

然後@DigitalRoss的回答更適合你。 – steenslag

+0

編輯以符合所需的輸出。 – steenslag

0
def transform input 
    input.split.map do |w| 
    [ 
     if w == 'case1' 
     'add that' 
     else 
     'add these' + w 
     end, 
     'x' 
    ] 
    end.flatten[0..-2] 
end 

這將常常被寫爲:

def transform input 
    input.split.map do |w| 
    [ w == 'case1' ? 'add that' : 'add these' + w, 'x' ] 
    end.flatten[0..-2] 
end 
+0

更喜歡['flat_map'](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-flat_map)。flatten ' – dbenhur

+0

@dbenhur代碼如何用flat_map編寫? – Erandir

相關問題