Console Input & Output in Ruby
Learn how to print output to the console and read input from the user using puts, print, p, and gets in Ruby.
Console Output Basics
Ruby gives you three main ways to print output: `puts` adds a newline, `print` does not, and `p` shows the raw value — great for debugging.
1. puts — Print with Newline
`puts` converts the value to a string and adds a newline at the end.
2. print — Print Without Newline
`print` outputs the value but does NOT add a newline, so the cursor stays on the same line.
3. p — Debug Output
`p` prints the raw Ruby representation of a value — strings include quotes, nil shows as `nil`.
4. pp — Pretty Print
`pp` is like `p` but formats complex objects like nested hashes and arrays in a readable way.
Printing Using $stdout
Ruby's `$stdout` is the global standard output stream. You can write to it directly using `$stdout.write` or `$stdout.puts` — useful when you need low-level control.
1. $stdout.write
`$stdout.write` sends raw bytes — no newline, no conversion. Returns the number of bytes written.
2. $stdout.flush — Force Output
Ruby buffers output. `$stdout.flush` forces it to appear immediately — useful for progress indicators.
Formatted Console Output
Ruby offers string interpolation with `#{}`, `sprintf`/`format` for printf-style formatting, and `printf` for direct formatted printing.
1. String Interpolation
Embed any Ruby expression inside a string using `#{}`.
2. sprintf / format
`sprintf` (aliased as `format`) returns a formatted string using printf-style placeholders.
3. printf — Formatted Print
`printf` prints a formatted string directly — like `sprintf` but outputs immediately.
Console Input (Reading User Data)
Ruby reads user input from the terminal using `gets`. The input always comes as a string with a trailing newline, so use `chomp` to remove it.
1. gets.chomp — Read a Line
`gets` reads one line of input. `chomp` removes the trailing newline `\n`.
2. Reading a Number
`gets` always returns a String. Use `.to_i` or `.to_f` to convert to a number.
3. Reading Multiple Inputs
Call `gets.chomp` multiple times to collect several values from the user.