shin
shin

Reputation: 32721

How to add , between 00, 000, 11, 111 etc in Ruby

I have a string input and I'd like insert , between 00 and 11 like the following example.

input1 = '00011010100011101'
desired_result1 = '0,0,01,101010,0,01,1,101'

input2 = '11010111101010000001011'
desired_result2 = '1,10101,1,1,101010,0,0,0,0,0101,1'

I tried the following but it doesn't give me what I want.

input1.gsub(/00/,'0,0').gsub(/11/,'1,1')
=> "0,001,101010,001,1101"

I appreciate any inputs.

Note Answers to this question may be later silently used here without credits.

Upvotes: 3

Views: 91

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110725

Look, ma, no gsub, no regex!

def insert_commas(str)
  ([str[0]] + str.chars.each_cons(2).map { |a,b| a==b ? ','+b : b }).join('')
end

insert_commas('00011010100011101')
  #=> "0,0,01,101010,0,01,1,101"
insert_commas('11010111101010000001011')
  #=> "1,10101,1,1,101010,0,0,0,0,0101,1"

Upvotes: 3

spickermann
spickermann

Reputation: 107037

input.gsub(/(00+|11+)/) { |m| m.split(//).join(',') }
# => "0,0,01,101010,0,01,1,101"

Upvotes: 3

Theo
Theo

Reputation: 132922

One way of doing it is by using a lookbehind ((?<=...)). This is a zero-width assertion that isn't captured, so you can match on a 1 that is preceeded by a 1, or a 0 preceeded by 0:

input.gsub(/(?<=1)1|(?<=0)0/, ',\0')

\0 is the matched string, i.e. a 1 or 0, but not the 1 or 0 preceding it.

Here is a good guide on lookahead and lookbehind.

Upvotes: 5

Uri Agassi
Uri Agassi

Reputation: 37409

Generaling @spickermann's solution:

input1.gsub(/(.)\1+/) { |m| m.split('').join(',') }
# => "0,0,01,101010,0,01,1,101" 

Upvotes: 2

Related Questions