If you're learning Ruby, you'll probably see and use puts, print, and p methods a lot.
However, there are many people who do not fully understand the differences between them.
Because I was one of them.
In some reference books, puts is used to output character strings, but in other learning contents, p is used for output. When I thought about it, I learned that there is also a print method.
At that time, I was just starting to learn Ruby, and I didn't know the difference between them, so I was confused because I didn't know which one to use.
In this article, we will explain the three methods of puts print p for such people!
It's not that difficult, so let's learn it easily!
Simply put, the difference between the puts, print, and p methods lies in the target audience.
Puts and print are for general users, and p is for developers. What this means is who the value you want to output is for.
For example, suppose you have an application that you developed yourself. Use puts or print if you want to see something for the user as the application runs.
However, it should be noted here that print does not break the content of what you want to print.
It can be said that it is very inconvenient for both the developer side and the user side that line breaks are not performed when some long sentences are output.
Therefore, in general, puts is used when outputting to general users.
On the other hand, p is a method for developers.
The big difference from puts and print of p is that the object passed as an argument is the return value as it is.
For example, it looks like this:
#Do the following: Also, for the sake of clarity, the description for executing with irb etc. is omitted.
p "Output with double quotes included"
"Output with double quotes included" #Output contents
=>"Output with double quotes included"
#When output with puts
puts "Output with double quotes included"
Output with double quotes included#Output contents
=> nil
How about that? You may have found that there is a big difference between the three methods.
I've found that the puts, print, and p methods each handle the same arguments but display different output results.
From a beginner's point of view, it is recommended to pay attention to each target user.
You can easily use the puts method if you want the output content for general users, and the p method if you want the output content for developers.
Recommended Posts