Output with print and p
Part of the Fundamentals section of Coddy's Ruby journey — lesson 27 of 88.
Ruby gives you two more ways to display output: print and p. Each behaves differently from puts.
The print method outputs text without adding a new line at the end:
print "Hello"
print "World"This outputs:
HelloWorldNotice how both words appear on the same line. This is useful when you want to build output piece by piece without automatic line breaks.
The p method is different. It shows the raw, debug-friendly version of a value:
puts "Hello"
p "Hello"This outputs:
Hello
"Hello"With p, strings appear with their quotation marks, making it clear you're looking at a string. This is helpful when debugging because you can see exactly what type of data you're working with.
Challenge
EasyUse print and p to display output in the following ways:
- Use
printto outputRubyfollowed by anotherprintto outputProgramming(both should appear on the same line with no space between them), then use a bareputs(with no arguments) to move to the next line - Use
pto output the stringdebug(showing its raw form with quotation marks) - Use
pto output the number42
Your output should be exactly 3 lines total:
RubyProgramming<br>"debug"<br>42Cheat sheet
Ruby provides print and p as alternatives to puts for displaying output.
The print method outputs text without adding a new line:
print "Hello"
print "World"
# Outputs: HelloWorldThe p method displays the raw, debug-friendly version of a value, showing strings with quotation marks:
puts "Hello" # Outputs: Hello
p "Hello" # Outputs: "Hello"This makes p useful for debugging, as it clearly shows the data type you're working with.
Try it yourself
# TODO: Write your code below
# 1. Use print twice to output "Ruby" and "Programming" on the same line,
# then use a bare puts (with no arguments) to move to the next line
# 2. Use p to output the string "debug"
# 3. Use p to output the number 42This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False