Narendra522
Narendra522

Reputation: 167

How to convert a number in a string to an integer

I have an output like "35%" from one command, and I stripped "%". Still, it's stored as a string. Is there a function to convert the string to integer?

Upvotes: 0

Views: 99

Answers (2)

Cyprus
Cyprus

Reputation: 1

Let's say your string is "35%". Start reading your string character by character. First your pointer is at '3'. Subtract '0'(ASCII 0) from this and multiply the result by 10. Go to the next character, '5' in this case and again subtract '0' but multiply the result by 1. Now add the 2 results and what you get is integer type 35. So what you are basically doing is subtracting '0' from each character and multiplying it by 10^(its position), until you hit your terminator(% here).

Upvotes: 0

Abdul Baig
Abdul Baig

Reputation: 3721

You can simply do "35%".to_i which produces 35


For your exact problem:

puts 'true' if 35 == "35".to_i

output is:

true

Upvotes: 3

Related Questions