Dave
Dave

Reputation: 19150

How do I use 'gsub' to make multiple substiuttions?

I have a string that only contains one number on either side of "-", like:

"1-3"

I want to get a result like

"01-03"

If the string had two numbers on one side of the dash like:

"1-10"

then I don't want to make any substitutions. I could do a gsub expression like

str.gsub!(/(^|[^\d]])\d[[:space:]]*\-[[:space:]]*\d([^\d]|$)/, '\1')

but I'm not clear how to do it if there are multiple (e.g. two) things to substitute.

Upvotes: 1

Views: 112

Answers (4)

dawg
dawg

Reputation: 103844

You can do:

def nums(s)
   rtr=s[/^(\d)(\D+)(\d)$/] ? '0%s%s0%s' % [$1,$2,$3] : s
end 

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110685

This is a variant of @TomLord's answer.

def pad_single_digits(str)
  str.size > 3 ? str : "0%d-0%d" % str.split('-')
end

pad_single_digits "1-3"  #=> "01-03"
pad_single_digits "1-10" #=> "1-10"

"0%s-0%s" also works.

Upvotes: 1

Tom Lord
Tom Lord

Reputation: 28305

Is there really a need to use regex here, at all? Seems like an over-complication to me. Assuming you know the string will be in the format: <digits><hyphen><digits>, you could do:

def pad_digits(string)
  left_digits, right_digits = string.split('-')
  if left_digits.length > 1 || right_digits.length > 1
    string
  else
    "%02d-%02d" % [left_digits, right_digits]
  end
end

pad_digits("1-3") # => "01-03"
pad_digits("1-10") # => "1-10"

Upvotes: 2

tadman
tadman

Reputation: 211590

You could probably get away with this:

def dashreplace(str)
  str.sub(/\b(\d)\-(\d)\b/) do |s|
    '%02d-%02d' % [ $1.to_i, $2.to_i ]
  end
end

dashreplace('1-2')
# => "01-02"
dashreplace('1-20')
# => "1-20"
dashreplace('99-1,2-3')
# => "99-1,02-03"

Upvotes: 3

Related Questions