Andrew Kim
Andrew Kim

Reputation: 3335

Use gsub to insert a dash to two odd numbers

I want my program to replace any pattern of two odd numbers together to enter a dash in between them

My original thought was to utilize gsub but,

num.gsub(/[13579][13579]/, '\1-\1')

but this just netted me to get a dash before one odd number, i.e:

'575'.gsub(/[13579][13579]/, '\1-\1')
#=> -5

I want it to output 5-7-5. I want a number like 12457 to output as 1245-7

Upvotes: 0

Views: 527

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

I prefer @YuHao's answer, but here's a way that does not use a regex:

def insert_dashes(str)
  str.chars
     .each_cons(2)
     .map { |i,j| (i.to_i.odd? && j.to_i.odd?) ? i+'-' : i }
     .join + str[-1]
end

insert_dashes('575')          #=> "5-7-5"
insert_dashes('12457')        #=> "1245-7"
insert_dashes('417386523792') #=> "41-7-386523-7-92"

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122463

Adding grouping '575'.gsub(/([13579])[13579]/, '\1-\1') would output "5-55", but that's still incorrect.

You can use zero-width positive lookahead like this:

'575'.gsub(/([13579])(?=[13579])/, '\1-')
#=> "5-7-5"
'12457'.gsub(/([13579])(?=[13579])/, '\1-')
#"1245-7"

Upvotes: 2

Related Questions