input = AA-AA-AA-AA-AA-AA
我如何能
- 将奇数 (1st, 3rd, 5th) 替换为
:
- 将偶数 (2nd, 4th) 事件替换为
.
input.gsub("-").with_index(1){|_, i| i.odd? ? ":" : "."}
# => "AA:AA.AA:AA.AA:AA"
这是一种方法,尽管它不是您可能正在寻找的单线:
input = 'AA-AA-AA-AA-AA-AA'
input.count('-').times do |i|
replacement = i.even? ? ':' : '.'
input.sub!('-', replacement)
end
input
# => "AA:AA.AA:AA.AA:AA"
count= 0
input.gsub!(/\-/) do |s|
count+= 1; s= count% 2== 0 ? '.' : ':'
end
input = "AA-AA-AA-AA-AA-AA".gsub("AA-AA", ":-.")
也许?