2011-03-30 69 views
0

我使用紅寶石1.9.2。分裂相關功能

gsub/scan迭代超過給定正則表達式/字符串匹配,並以三種方式使用:

  1. 如果scan沒有塊被使用時,它返回匹配的陣列。
  2. 如果scan與塊一起使用,它會迭代匹配並執行某些操作。
  3. 如果使用gsub,它會將第二個參數或塊的匹配項替換爲匹配項,並返回一個字符串。

在另一方面,有什麼gsub/scan匹配的互補匹配split。然而,只有一個用這種方式:

  1. 如果split沒有一個塊時,它返回匹配的互補的數組。

我想要另外兩個與split相關的缺失用法,並試圖實現它們。以下every_other延伸split,以便它可以使用像scan

class String 
    def every_other arg, &pr 
    pr ? split(arg).to_enum.each{|e| pr.call(e)} : split(arg) 
    end 
end 

# usage: 
'cat, two dogs, horse, three cows'.every_other(/,\s*/) #=> array 
'cat, two dogs, horse, three cows'.every_other(/,\s*/){|s| p s} # => executes the block 

然後,我試圖執行的gsub對方,但不能把它做好。

class String 
    def gsub_other arg, rep = nil, &pr 
    gsub(/.*?(?=#{arg}|\z)/, *rep, &pr) 
    end 
end 

# usage 
'cat, two dogs, horse, three cows'.gsub_other(/,\s*/, '[\1]') # or 
'cat, two dogs, horse, three cows'.gsub_other(/,\s*/) {|s| "[#{s}]"} 

# Expected => "[cat], [two dogs], [horse], [three cows]" 
# Actual output => "[cat][],[ two dogs][],[ horse][],[ three cows][]" 
  • 我在做什麼錯?
  • 這種方法是否正確?有沒有更好的方法來做到這一點,或者有沒有方法可以做到這一點?
  • 你有關於方法名稱的建議嗎?

回答

0

這不是漂亮,但是這似乎工作

s='cat, two dogs, horse, three cows' 
deli=",\s" 
s.gsub(/(.*?)(#{deli})/, '[\1]\2').gsub(/(.*\]#{deli})(.*)/, '\1[\2]') 

=> "[cat], [two dogs], [horse], [three cows]" 

以下感覺好一點

s.split(/(#{deli})/).map{|s| s!=deli ? "[#{s}]" : deli}.join 
+0

感謝您的回答,但我想要一個迭代器,是有效的,可以使用通常。我對我給出的具體例子不感興趣。 – sawa 2011-03-31 00:17:00