A number comes in as a string, such as "000105"
, and I'm trying to find a good way to ignore the leading zeroes. A RegEx comes to mind, but sometimes those can get hard to read. What I do currently is:
stack = "000105" # => "000105"
overflow = stack.to_i.to_s # => "105"
Is there some easier/elegant way to do this? It feels clunky to convert this string to an integer and back to string.
I would use String#sub
:
overflow = stack.sub(/^0+/, '')
or just String#sub!
if a want to change stack
:
stack.sub!(/^0+/, '')
In this sub
is better than gsub
, because it needs to match only once.