Let Me Tell You a Secret

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Numbers to Strings and Back Again | TOC | Getting Strings from the User 👉

There’s something strange about the puts method. Have a look at this:

​1: puts  20 
​2: puts 20.​to_s​
​3: puts ​"20"​
​<= 20
​ 20
​ 20

Why do these three all print the same thing? Well, the last two should, since 20.to_s is “20”. But what about the first example, the integer 20? For that matter, what does it even mean to write the integer 20? When you write a 2 and then a 0 on a piece of paper, you’re writing a string, not an integer. The integer 20 is the number of fingers and toes I have; it isn’t a 2 followed by a 0.

Well, here’s the big secret behind the puts method: before puts tries to write out an object, it uses to_s to get the string version of that object. In fact, the s in puts stands for string; puts actually means put string.

And here’s a bonus secret: string interpolation does the same thing. Check it out:

​1: puts ​"my favorite number really is ​​#{​2+3​}​​"​​<= my favorite number really is 5

This actually ends up being convenient, as it’s one less conversion that you have to think about.

Now let’s check out how you can get strings directly from the user, which will allow you to write all sorts of fun programs.

--

--

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.