Will Ashley Will Ashley - 1 year ago 80
Ruby Question

Ruby gsub match concatenation

Given a string of digits, I am trying to insert a - in-between odd numbers and a * in between even numbers. The solution below is very convoluted, and I was wondering if I could do something like this:

"99946".gsub(/[13579][13579]/) {|s,x| s+"-"+x}

Where s is the first odd, x is the second. Usually when I substitute, I am replacing the matched term, but here I want to keep the matched term and insert a character in-between the pattern. This would make this problem much simpler.

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(" ", "-")
array.join(" ").gsub(" ", "*")
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")

Answer Source

This will work for you:

"99946".gsub(/[13579]+/) {|s| s.split("").join("-") }
# => "9-9-946"

It's roughly similar to what you tried. It captures multiple consecutive odd digits, and uses the gsub block to split and then join them separated by the "-".

This will include both solutions working together:

"99946".gsub(/[13579]+/) {|s| s.split("").join("-") }.gsub(/[02468]+/) {|s| s.split("").join("*") }
# => "9-9-94*6"