分裂相关功能
问题描述:
我使用红宝石1.9.2。分裂相关功能
gsub
/scan
迭代超过给定正则表达式/字符串匹配,并以三种方式使用:
- 如果
scan
没有块被使用时,它返回匹配的阵列。 - 如果
scan
与块一起使用,它会迭代匹配并执行某些操作。 - 如果使用
gsub
,它会将第二个参数或块的匹配项替换为匹配项,并返回一个字符串。
在另一方面,有什么gsub
/scan
匹配的互补匹配split
。然而,只有一个用这种方式:
- 如果
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][]"
- 我在做什么错?
- 这种方法是否正确?有没有更好的方法来做到这一点,或者有没有方法可以做到这一点?
- 你有关于方法名称的建议吗?
答
这不是漂亮,但是这似乎工作
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
感谢您的回答,但我想要一个迭代器,是有效的,可以使用通常。我对我给出的具体例子不感兴趣。 – sawa 2011-03-31 00:17:00