Ruby Built-in Functions
Ruby Core Methods (Often Called Built-in Functions)
Section titled “Ruby Core Methods (Often Called Built-in Functions)”Ruby’s Kernel module is included by the Object class, making its methods available in virtually every part of a Ruby program. These methods can often be called without an explicit receiver (e.g., puts "hello" instead of self.puts "hello"), giving them a function-like appearance. This chapter provides an overview of commonly used Kernel methods and other essential core functionalities.
A selection of important Kernel methods:
| Method Signature(s) | Description |
|---|---|
abort(message=nil) | Terminates program execution immediately. If message is given, it’s printed to stderr. If an exception is active ($!), its message is displayed. |
Array(object) | Converts object to an Array. Calls to_ary if available, otherwise to_a. |
at_exit { block } | Registers a block to be executed when the program exits. Multiple blocks are executed in reverse order of registration. |
autoload(module_name, filename) | Registers filename to be loaded (using require) the first time module_name (a String or Symbol) is referenced. |
binding | Returns a Binding object representing the current execution context (variables, methods, self). Useful with eval. |
block_given? | Returns true if the current method was called with a block, false otherwise. |
caller(start=1, length=nil) | Returns the current execution stack (backtrace) as an array of strings in the format file:line: in method`. |
catch(tag) { block } | Provides a way to perform a non-local exit (jump) from a block. Used with throw(tag, value). |
eval(string, binding=TOPLEVEL_BINDING, filename="(eval)", lineno=1) | Executes the Ruby code in string. binding specifies the context. Use with extreme caution due to security risks with untrusted input. |
exec(command, *args) | Replaces the current process with the specified command. Does not return if successful. |
exit(status=true) / exit!(status=true) | exit terminates the script, running at_exit handlers and ensure clauses. exit! terminates immediately without running handlers. status can be an integer exit code (0 for success) or true/false. |
Float(arg, exception: true) | Converts arg to a Float. Raises an exception on failure unless exception: false. |
fork { block } | Creates a child process. The block is executed in the child. Returns the child’s PID in the parent, nil in the child. Not available on all platforms (e.g., standard Windows Ruby). |
format(format_string, *args) / sprintf(format_string, *args) | Returns a string formatted according to format_string and args. See formatting directives below. |
gets(separator=$/) | Reads the next line from standard input (or files specified on command line via ARGF). separator is the line ending. Returns nil at EOF. |
global_variables | Returns an array of Symbols representing the names of all defined global variables. |
Integer(arg, base=0, exception: true) | Converts arg to an Integer. base specifies the numerical base. Raises an exception on failure unless exception: false. |
lambda { block } / proc { block } | Creates a Proc object from block. lambdas have stricter argument checking and different return behavior than procs made with Proc.new or proc keyword. |
load(filename, wrap=false) | Loads and executes the Ruby program in filename. Unlike require, load can execute a file multiple times and doesn’t track loaded files. If wrap is true, loads into an anonymous module. |
local_variables | Returns an array of Symbols representing the names of currently defined local variables. |
loop { block } | Repeats the block indefinitely until explicitly broken out of (e.g., with break or an exception). |
open(path, mode="r", &block) | Opens a file specified by path with the given mode. If a block is given, the file object is passed to the block and automatically closed when the block finishes. If path starts with |, it’s treated as a command for piped I/O. |
p(obj1, obj2, ...) | For each object, prints obj.inspect followed by a newline to $stdout. Useful for debugging. |
print(*args) | Prints each arg to $stdout after calling to_s on it. Does not add a newline by default. Prints $_ if no arguments given. |
printf(format_string, *args) / printf(io, format_string, *args) | Formats arguments according to format_string (like sprintf) and prints to $stdout or a specified io object. |
puts(*args) | Prints each arg to $stdout, adding a newline after each (unless the arg itself is an array, in which case each element is printed on a new line). Calls to_s on args. |
raise(exception_class, message, backtrace) / fail(...) | Raises an exception. fail is an older alias for raise; prefer raise. Can re-raise current exception if called with no arguments inside a rescue clause. |
rand(max=0.0) | Generates a pseudo-random number. If max is an Integer > 0, returns an integer from 0 to max-1. If max is a Float or 0, returns a float between 0.0 and 1.0 (exclusive of 1.0). If max is a Range, returns a random element from that range. |
readline(separator=$/) | Similar to gets, but raises EOFError at end of file. |
readlines(separator=$/) | Reads all lines from standard input (or ARGF) and returns them as an array of strings. |
require(name) / require_relative(name) | require loads a given library/file (name) once. It searches Ruby’s load path. Used for gems and standard libraries. require_relative loads a file relative to the current file’s directory. |
select(read_array, write_array=nil, error_array=nil, timeout=nil) | Performs low-level I/O multiplexing. Checks for I/O readiness on arrays of IO objects. |
sleep(duration) | Suspends execution for duration seconds (can be a float). If no argument, sleeps forever. |
String(arg) | Converts arg to a String by calling to_s. |
system(command, *args) | Executes command in a subshell. Returns true if the command exits with status 0, false otherwise, and nil if command execution fails. The exit status is available in $?. |
test(cmd, file1, file2=nil) | Performs file tests. cmd is a character specifying the test (e.g., ?f for regular file). Prefer File class methods (e.g., File.file?) for readability. |
throw(tag, value=nil) | Initiates a non-local exit, jumping to the catch block with the matching tag. value becomes the return value of catch. |
trap(signal, command_or_proc) | Sets up a handler for an operating system signal (e.g., 'INT', 'TERM'). |
Common Numeric and Integer Methods
Section titled “Common Numeric and Integer Methods”These methods are available on numeric objects (instances of Integer, Float, etc.).
#!/usr/bin/env rubynum_i = -10num_f = 12.75
puts "Integer methods:"puts "#{num_i}.abs: #{num_i.abs}" # => 10puts "#{num_i}.even?: #{num_i.even?}" # => trueputs "#{num_i}.odd?: #{num_i.odd?}" # => falseputs "5.next: #{5.next}" # => 6 (or 5.succ)puts "5.times { |i| print "#{i} " }: " ; 5.times { |i| print "#{i} " } ; puts
puts "\nFloat methods:"puts "#{num_f}.round: #{num_f.round}" # => 13puts "#{num_f}.floor: #{num_f.floor}" # => 12puts "#{num_f}.ceil: #{num_f.ceil}" # => 13puts "#{num_f}.truncate: #{num_f.truncate}" # => 12
puts "\nNumeric methods (available on both):"puts "#{num_i}.zero?: #{num_i.zero?}" # => falseputs "0.zero?: #{0.zero?}" # => trueputs "#{num_f}.positive?: #{num_f.positive?}" # => trueputs "#{num_i}.negative?: #{num_i.negative?}" # => trueSelected Numeric, Integer, Float methods:
| Method | Description |
|---|---|
n.abs | Returns the absolute value of n. |
n.ceil | Returns the smallest integer greater than or equal to n (Float). |
n.floor | Returns the largest integer less than or equal to n (Float). |
n.round([digits]) | Rounds n to the nearest integer, or to digits decimal places (Float). |
n.truncate([digits]) | Removes decimal part, returning an integer, or truncates to digits (Float). |
n.to_i / n.to_int | Converts n to an Integer (truncates for Floats). |
n.to_f | Converts n to a Float. |
n.integer? | Returns true if n is an Integer. |
n.float? | Returns true if n is a Float. |
n.zero? | Returns true if n is zero. |
n.positive? | Returns true if n is greater than zero. |
n.negative? | Returns true if n is less than zero. |
int.even? | Returns true if int is an even integer. |
int.odd? | Returns true if int is an odd integer. |
int.next / int.succ | Returns the integer int + 1. |
int.pred | Returns the integer int - 1. |
int.times { |i| ... } | Iterates the block int times, passing the current iteration number (0 to int-1). |
num.step(limit, step_value) { |i| ... } | Iterates from num up to (or down to) limit, incrementing by step_value. |
float.finite? | Returns true if float is a finite number. |
float.infinite? | Returns 1 for positive infinity, -1 for negative infinity, else nil. |
float.nan? | Returns true if float is Not a Number (NaN). |
Math Module Functions
Section titled “Math Module Functions”The Math module provides a collection of trigonometric, logarithmic, and other mathematical functions. These are typically called as Math.function_name(argument).
| Function (in Math module) | Description |
|---|---|
Math.sqrt(x) | Returns the non-negative square root of x (x must be non-negative). |
Math.log(x) / Math.log(x, base) | Returns the natural logarithm of x, or logarithm of x to base. |
Math.log10(x) | Returns the base-10 logarithm of x. |
Math.exp(x) | Returns e (Euler’s number) raised to the power of x. |
Math.sin(x), Math.cos(x), Math.tan(x) | Trigonometric sine, cosine, tangent of x (in radians). |
Math.asin(x), Math.acos(x), Math.atan(x) | Inverse trigonometric functions. |
Math.atan2(y, x) | Arc tangent of y/x, using signs of x and y to determine quadrant. |
Math::PI | Constant for Pi (approx. 3.14159…). |
Math::E | Constant for Euler’s number (approx. 2.71828…). |
Example:
#!/usr/bin/env rubyputs "Square root of 16: #{Math.sqrt(16)}" # => 4.0puts "PI: #{Math::PI}"puts "Cosine of PI: #{Math.cos(Math::PI)}" # => -1.0sprintf/format Conversion Specifiers
Section titled “sprintf/format Conversion Specifiers”The sprintf (or format) method uses conversion specifiers in a format string to determine how arguments are formatted. A specifier starts with % and can include flags, width, precision, and a type character.
Common type characters:
| Specifier | Description |
|---|---|
b | Binary integer (base 2). |
c | Character (treats integer argument as character code). |
d or i | Decimal integer (base 10). |
u | Unsigned decimal integer. |
o | Octal integer (base 8). |
x | Hexadecimal integer (lowercase a-f). |
X | Hexadecimal integer (uppercase A-F). |
f | Floating-point number in fixed-point notation (e.g., 123.45). |
e | Floating-point number in scientific notation (e.g., 1.2345e+02). |
E | Like e, but uses uppercase E. |
g | Uses %e or %f format, whichever is shorter. |
G | Uses %E or %f format, whichever is shorter. |
s | String (calls to_s on the argument). |
p | Prints object using inspect (Ruby specific). |
% | A literal percent sign (%%). |
Flags, width, and precision examples:
#!/usr/bin/env rubyputs sprintf("Number: %d, String: %s", 123, "hello") # => "Number: 123, String: hello"puts sprintf("Padded: %05d", 42) # => "Padded: 00042" (zero-padded, width 5)puts sprintf("Float: %.2f", 123.4567) # => "Float: 123.46" (2 decimal places)puts sprintf("Hex: %x", 255) # => "Hex: ff"puts sprintf("Left-justified: |%-10s|", "text") # => "Left-justified: |text |"test Function Arguments (Prefer File Class Methods)
Section titled “test Function Arguments (Prefer File Class Methods)”The test(cmd, file1, file2) function performs file tests. While available, it’s generally recommended to use the more readable and object-oriented methods from the File class (e.g., File.readable?(file1), File.exist?(file1)).
For further details on specific methods, always refer to the official Ruby documentation for the Kernel, Numeric, Integer, Float, and Math modules/classes. (Ruby Core Documentation)