Ruby Output
Output is what a program prints. puts, print and p print in three different ways.
puts ends the line
puts adds a newline after Ana. Mina starts on a new line.
puts "Ana"
puts "Mina"print stays on the line
print adds no newline after Ana. Mina prints right after it on the same line.
print "Ana"
print "Mina"p shows the inspected form
The inspected form shows a value as it is written in code. The text Ana keeps its quotes in this form, and the number 42 stays plain.
p "Ana"
p 42nil two ways
puts prints nil as an empty line. p prints nil as the word nil.
puts nil
p nilAn array two ways
An array is a list of values in square brackets. puts prints one item per line, and p prints the array as one value.
puts [1, 2, 3]
p [1, 2, 3]Example
puts "First"
print "Second "
puts "Third"
p "Fourth"Key points
- puts adds a newline after the value it prints.
- print prints a value with no newline after it.
- p prints a value in its inspected form.
- A String keeps its quotes in its inspected form.
- puts prints nil as an empty line.
- p prints nil as the word nil.
- puts prints each item of an array on its own line.
In this example, puts prints First on its own line. print prints Second with no newline, so the puts line prints Third on that same line. p then prints Fourth in its inspected form, with quotes.
Note
Most programs in this course print with puts.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
Which word prints a value with no newline after it?