0

How to sum str and num in Ruby?
And return string again.
In a way to preserve the zeros in the beginning of the string.

Example:

str = "001"  
num = 3

Expected result:

str + num #=> "004"
Stefan
  • 109,145
  • 14
  • 143
  • 218
user815693
  • 516
  • 1
  • 6
  • 12
  • duplicate: http://stackoverflow.com/questions/11466988/ruby-convert-string-to-integer-or-float . also you could be more clear in the fact that this is ruby in the text of your question. – ramrunner Feb 27 '15 at 03:41
  • 2
    I don't agree that it's a duplicate. – Cary Swoveland Feb 27 '15 at 06:18
  • Some context would help. Where do `str` and `num` come from, why do you have to preserve the zeroes, what are you doing with the result? – Stefan Feb 27 '15 at 09:33
  • For `num = 20`, is the expected result `"021"` or `"0021"` – Stefan Feb 27 '15 at 09:35

3 Answers3

4

If you don't mind modifying str, you could do this:

3.times { str.next! }
str #=> "004"

If you don't want to modify str, operate on str.dup.

Alternatively:

3.times.reduce(str) { |s,_| s.next }
  str #=> "004"

which does not mutate str.

I know what you're thinking: this isn't very efficient.

Edited to incorporate Stefan's first suggestion. Initially I implemented his second suggestion as well, but I've gone back to next and next!. I just think next reads better than succ, and they're clearly methods, so I'm not worried about them being confused with the next keyword.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

Use to_i to convert str to an integer, add num to it, then convert the resulting integer to a string with to_s. Zero padding is done using rjust().

str = "001"  
num = 3
(str.to_i + num).to_s.rjust(3, '0')
=> "004"
mhawke
  • 84,695
  • 9
  • 117
  • 138
0
def sum_string(string, number)
    return string.scan(/^0*/)[0]+(string.to_i+number).to_s  
end
puts sum_string("00030", 5)

puts sum_string("00006", 7) 
    returns 000013 which is adding one more zero at the beginning

So, this is a slight improvement

def sum_string(string, number)
    len = (string.scan(/^0*/)[0]+(string.to_i+number).to_s).length - string.length
    if len > 0 then
        return string.scan(/^0*/)[0][len..-1]+(string.to_i+number).to_s 
    else
        return string.scan(/^0*/)[0]+(string.to_i+number).to_s  
    end
end
user815693
  • 516
  • 1
  • 6
  • 12