Reputation: 516
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"
Upvotes: 0
Views: 282
Reputation: 110735
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.
Upvotes: 4
Reputation: 516
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
Upvotes: 0
Reputation: 87134
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"
Upvotes: 1