About the to_s method.

Description of the to_s method

** A method that numbers have. It converts numbers to strings. By the way, the meaning of s in to_s is "string". ** ** See the example below.

[Example] irb


#To the number "20"_Execute with s method
irb(main):001:0> 20.to_s
=> "20"

The string "20" is the execution result by the to_s method.

Now, let's concatenate the strings and numbers, Let's display "i am 20 years old."

Let's run the following code in irb

Now, let's actually try the to_s method in the terminal.

Terminal


# to_Convert a number to a string with s and concatenate
irb(main):001:0> "i am " + 20.to_s + " years old."

#If it continues to be displayed like this, it is successful
=> i am 20 years old.

You might think, "I should have prepared the character string " 20 "</ font> from the beginning." Maybe. However, if you want to use the result of addition as a character string, etc. There are many occasions when you use the ** to_s method ** </ font> to convert a number to a string. Be sure to remember this method.

On the contrary, there is also a method to convert a string to a number. That is the to_i method. This is the method that strings have. I will explain the to_i method next time.

Summary

** The to_s method is a method that converts a number to a character string. ** **

that's all.

Recommended Posts