【发布时间】:2016-05-20 22:41:51
【问题描述】:
给定一串数字,我试图在奇数之间插入'-',在偶数之间插入'*'。解决方法如下:
def DashInsertII(num)
num = num.chars.map(&:to_i)
groups = num.slice_when {|x,y| x.odd? && y.even? || x.even? && y.odd?}.to_a
puts groups.to_s
groups.map! do |array|
if array[0].odd?
array.join(" ").gsub(" ", "-")
else
array.join(" ").gsub(" ", "*")
end
end
d = %w{- *}
puts groups.join.chars.to_s
groups = groups.join.chars
# Have to account for 0 because Coderbyte thinks 0 is neither even nor odd, which is false.
groups.each_with_index do |char,index|
if d.include? char
if (groups[index-1] == "0" || groups[index+1] == "0")
groups.delete_at(index)
end
end
end
groups.join
end
非常复杂,我想知道我是否可以这样做:
"99946".gsub(/[13579][13579]/) {|s,x| s+"-"+x}
其中s 是第一个奇数,x 第二个。通常当我替换时,我会替换匹配的术语,但这里我想保留匹配的术语并在模式之间插入一个字符。这将使这个问题变得更简单。
【问题讨论】:
-
你读过docs for
String#gsub吗?他们清楚地解释了如何在替换中使用捕获的字符串。
标签: ruby regex substitution