Reputation: 13
I am entering "901000"
as an argument to the following method, and I expect it to remove the last three zeros and return "901"
.
def zeros(x)
str = x.to_s
i = str.length-1
while str[i] == "0"
str = str.delete(str[i])
i = i-1
end
return str
end
But it returns "91"
instead. I cannot understand why my code does not work. Can someone help please?
Upvotes: 1
Views: 728
Reputation: 168111
At first, str
is "901000"
, i = str.length-1
is 5
, and str[i]
is "0"
. Hence,
str = str.delete(str[i])
is equivalent to
str = "901000".delete("0")
That gives you "91"
.
Then, by i = i-1
, i
becomes 4
, and str[i]
(which is equivalent to "91"[4]
) becomes nil
, and str[i] == 0
(which is equivalent to nil == 0
) becomes false
. So the loop ends, returning the value str
, which is "91"
.
To do what you want, some simple ways are:
"901000".sub(/0+\z/, "") # => "901"
"901000"[/.*?(?=0+\z)/] # => "901"
Upvotes: 3