Readline
Readline.readline(prompt = nil) Returns:
String or nil · Updated March 13, 2026 · Modules input interactive cli readline
The Readline module provides command-line editing capabilities for interactive programs, similar to bash or IRB. It enables features like arrow key navigation, history, and Emacs/vi editing modes.
Basic Usage
require 'readline'
# Simple prompt
input = Readline.readline("> ")
puts "You entered: #{input}"
Interactive Input
require 'readline'
# Complete line editing
while line = Readline.readline("Enter command: ", true)
break if line.nil? || line.downcase == 'exit'
puts "Processing: #{line}"
end
With History
require 'readline'
# Enable history
Readline::HISTORY.push("first command")
Readline::HISTORY.push("second command")
# Read with history (second param true)
line = Readline.readline("> ", true)
puts line
puts "History: #{Readline::HISTORY.to_a}"
Completion
require 'readline'
# Basic completion
words = %w[apple banana cherry date elderberry]
Readline.completion_append_character = " "
completer = lambda do |str|
words.grep(/^#{Regexp.escape(str)}/)
end
Readline.completion_proc = completer
input = Readline.readline("Fruit: ")
Complex Completion
require 'readline'
# File completion
Readline.completion_proc = lambda do |str|
Dir.glob("#{str}*").map { |f| f + (File.directory?(f) ? "/" : " ") }
end
Configuration
# Edit mode (Emacs or Vi)
Readline.emacs_editing_mode # Default
Readline.vi_editing_mode # Vi-style
# Configure
Readline.basic_word_break_characters = " \t\n\"\\'`><=|&{"
Readline.completion_append_character = " "
Practical CLI Application
#!/usr/bin/env ruby
require 'readline'
COMMANDS = %w[help status start stop restart]
def prompt
Readline.readline("> ", true) do |line|
Readline::HISTORY.push(line)
process_command(line)
end
end
def process_command(line)
cmd = line.strip.split.first
case cmd
when 'help'
puts "Available: #{COMMANDS.join(', ')}"
when 'status'
puts "Running"
else
puts "Unknown command: #{cmd}"
end
end
prompt until Readline::HISTORY.empty? || false
Readline Extensions
# Using rb-readline for cross-platform
# gem install rb-readline
require 'rbreadline'
# Same API, works on Windows
Return Values
# Returns string, or nil on EOF (Ctrl+D)
line = Readline.readline("> ")
if line
puts "Got: #{line}"
else
puts "Goodbye!"
end
The Readline module is essential for building polished interactive command-line applications in Ruby.