Numbers to Strings and Back Again

Learn to Program, Third Edition — by Chris Pine (24 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 4 Conversions and Input | TOC | Let Me Tell You a Secret 👉

To get the string version of an object, you simply write .to_s after it like this:

​1: var1 =  2 
​2: var2 = ​"5"​
​3: puts var1.​to_s​ + var2
​<= 25

Similarly, appending .to_i gives the integer version of an object, and .to_f gives the float version. Let’s look at what these methods do (and don’t do) a little more closely:

​1: var1 =  2 
​2: var2 = ​"5"​
​3: puts var1.​to_s​ + var2
​4: puts var1 + var2.​to_i​
​<= 25
​ 7

Notice that, even after you got the string version of var1 by calling to_s, var1 was always pointing at 2 and never at “2”. Unless you explicitly reassign var1 (which requires an = sign), it’ll continue to point at 2 for the life of the program.

Let’s try some more interesting (and a few just plain weird) conversions:

​1: puts ​"15"​.​to_f​
​2: puts ​"99.999"​.​to_f​
​3: puts ​"99.999"​.​to_i​
​4: puts ​""​
​5: puts ​"5 is my favorite number!"​.​to_i​
​6: puts ​"Who asked you about 5 or whatever?"​.​to_i​
​7: puts ​"Your mama did."​.​to_f​
​8: puts ​""​
​9: puts ​"stringy"​.​to_s​
​10: puts 3.​to_i​
​<= 15.0
​ 99.999
​ 99

​ 5
​ 0
​ 0.0

​ stringy
​ 3

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.