0
0
RubyHow-ToBeginner · 3 min read

How to Use print in Ruby: Syntax and Examples

In Ruby, you use print to display text or variables on the screen without adding a new line at the end. Just write print 'your text' and it will show the text exactly as given.
📐

Syntax

The print method outputs text or values to the screen without adding a newline at the end. You can pass strings, numbers, or variables inside parentheses or without them.

  • print 'text': prints the text as is
  • print(variable): prints the value of a variable
ruby
print 'Hello, world!'
Output
Hello, world!
💻

Example

This example shows how print outputs text and variables without moving to a new line, so multiple prints appear on the same line.

ruby
print 'Hello, '
print 'Ruby!'
print 123
Output
Hello, Ruby!123
⚠️

Common Pitfalls

A common mistake is expecting print to add a newline after output. Unlike puts, print does not add a line break, so outputs run together unless you add it manually.

Also, forgetting quotes around strings causes errors.

ruby
print 'Hello'
print 'World'

# Correct way to add newline manually:
print "Hello\n"
print "World\n"
Output
HelloWorld Hello World
📊

Quick Reference

  • print: outputs text without newline
  • puts: outputs text with newline
  • Use \n inside strings to add newlines manually with print

Key Takeaways

Use print to display text without adding a newline.
Remember print keeps output on the same line unless you add \n.
Always put strings inside quotes when using print.
Use puts if you want to add a newline automatically.
You can print variables or expressions directly with print.