Kernel#putc
putc(obj) -> obj Returns:
Object · Updated March 13, 2026 · Kernel Methods output io characters printing
The putc method outputs a single character to STDOUT. Unlike puts which outputs strings with a newline, putc writes exactly one character and returns the object that was passed to it.
How It Differs from puts
puts "hello" # Outputs: hello\n and returns nil
putc "hello" # Outputs: h and returns "hello"
puts "A" # Outputs: A\n
putc "A" # Outputs: A
Practical Examples
Basic Character Output
# Output a single character
putc "A" # Prints: A
# With integers - outputs the character with that ASCII code
putc 65 # Prints: A (ASCII 65)
putc 97 # Prints: a (ASCII 97)
putc 10 # Prints: newline
# String input - only first character
putc "hello" # Prints: h
Building Output Character by Character
# Create a progress indicator
progress = ["|", "/", "-", "\\"]
5.times do |i|
print "\rProcessing #{progress[i % 4]}"
putc "\r" # Carriage return to overwrite
sleep 0.5
end
puts "\nDone!"
Writing to a File
# Putc works with any IO object
File.open("output.txt", "w") do |f|
putc f, "H"
putc f, "i"
putc f, "\n"
end
# File contains: Hi
Low-Level Character Handling
# Convert number to character
putc 0x41 # Hex 41 = 65 = 'A', outputs: A
# Binary data handling
bytes = [0x48, 0x65, 0x6C, 0x6C, 0x6F]
bytes.each { |b| putc b }
# Outputs: Hello
# Output character from variable
char = "X"
putc char # Outputs: X
Color Output in Terminal
# ANSI escape codes for colors
RED = "\e[31m"
RESET = "\e[0m"
putc RED[0]
putc "R"[0]
putc RESET[0]
puts # Newline to complete
Return Value
# putc returns the object passed to it
result = putc "hello"
puts result # => hello
# This allows chaining (though unusual)
putc(putc("A")) # Outputs: AA, returns "A"
Common Uses
putc is useful when you need:
- Character-by-character output
- Building output incrementally
- Working with binary data
- Low-level terminal operations
It’s a lower-level method than puts or print, giving you direct control over exactly what bytes are written to the output stream.