puts, print and p

Contents
puts adds newline
print does not
p shows inspect
printf basics

puts adds newline

The puts method writes each argument on its own line by adding a newline automatically.

The classic printing primer shows the same call, and here is how it behaves with an array.

puts "one" puts "two" puts [1, 2]

ruby puts_demo.rb

one
two
1
2

print does not

The print method writes exactly what it receives, with no newline added.

Join fragments with print and add the newline yourself when the line is complete.

print "one, " print "two" print "\n"

ruby print_demo.rb

one, two

p shows inspect

The p method writes the inspect form, which reveals the type behind the value.

Quotes around one mean a string and brackets mean an array, so the structure stays visible.

p "one" p [1, "two"] p({ name: "Ada" })

ruby p_demo.rb

"one"
[1, "two"]
{:name=>"Ada"}

printf basics

The printf method formats values into a template with placeholders for strings and numbers.

Minus ten in %-10s pads the name to ten columns, and zero four in %04d pads the number with zeros.

printf("%-10s %04d\n", "Ada", 42)

ruby printf_demo.rb

Ada 0042

Next: Metaprogramming

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: