0
0
RubyHow-ToBeginner · 3 min read

How to Use puts in Ruby: Simple Output Guide

puts in Ruby is used to print text or values to the console followed by a new line. You simply write puts followed by the text or variable you want to display inside quotes or without quotes for variables.
📐

Syntax

The basic syntax of puts is simple:

  • puts "text": Prints the text with a new line.
  • puts variable: Prints the value of a variable with a new line.
  • puts expression: Prints the result of an expression.
ruby
puts "Hello, world!"
puts 123
puts 5 + 3
Output
Hello, world! 123 8
💻

Example

This example shows how puts prints strings, numbers, and expressions to the console, each on its own line.

ruby
name = "Alice"
age = 30
puts "Name: " + name
puts "Age: #{age}"
puts age + 5
Output
Name: Alice Age: 30 35
⚠️

Common Pitfalls

One common mistake is forgetting that puts adds a new line after printing, which can affect formatting. Another is using puts with variables without converting them to strings when concatenating, which causes errors.

Use string interpolation "#{variable}" or separate arguments with commas to avoid errors.

ruby
puts "Age: " + age.to_s  # This avoids error by converting age to string
puts "Age: #{age}"  # Correct way using interpolation
puts "Age:", age    # Correct way using comma
Output
Age: 30 Age: 30 Age: 30
📊

Quick Reference

UsageDescription
puts "text"Prints text with a new line
puts variablePrints variable value with a new line
puts expressionPrints result of expression with a new line
puts "#{variable}"Prints variable inside a string using interpolation
puts arg1, arg2Prints multiple arguments separated by spaces, each followed by a new line

Key Takeaways

Use puts to print text or values followed by a new line in Ruby.
String interpolation "#{variable}" helps print variables inside strings safely.
Avoid concatenating strings and numbers directly; use interpolation or commas instead.
puts automatically adds a new line after each output.
You can print multiple items by separating them with commas in puts.