Ruby Kernel Functions
EditRocket provides the following information on Kernel functions in the Ruby source code builder.
abort - Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.
Array Array(arg) - Returns arg as an Array. First tries to call arg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg (unless arg is nil).
at_exit - Converts block to a Proc object (and therefore binds it at the point of call) and registers it for execution when the program exits. If multiple handlers are registered, they are executed in reverse order of registration.
autoload? autoload(module, filename) - Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.
autoload autoload(module, filename) - Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.
binding - Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. Also see the description of class Binding.
block_given? - Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.
callcc - Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. See class Continuation for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.
caller caller(start=1) - "Returns the current execution stack---an array containing strings in the form ``file:line'' or ``file:line: in `method'''. The optional start parameter determines the number of initial stack entries to omit from the result."
catch catch(symbol) - catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.
chomp! chomp! => $_ or nil - Equivalent to $_.chomp!(string). See String#chomp!
chomp chomp => $_ - Equivalent to $_ = $_.chomp(string). See String#chomp.
chop! - Equivalent to $_.chop!.
chop - Equivalent to ($_.dup).chop!, except nil is never returned. See String#chop!.
eval eval(string [, binding [, filename [,lineno]]]) - Evaluates the Ruby expression(s) in string. If binding is given, the evaluation is performed in its context. The binding may be a Binding object or a Proc object. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.
exec exec(command [, arg, ...]) - Replaces the current process by running the given external command. If exec is given a single argument, that argument is taken as a line that is subject to shell expansion before being executed. If multiple arguments are given, the second and subsequent arguments are passed as parameters to command with no shell expansion. If the first argument is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).
exit!(fixnum=-1) - Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.
exit exit(integer=0) - Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.
fail raise - With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
Float Float(arg) - Returns arg converted to a float. Numeric types are converted directly, the rest are converted using arg.to_f. As of Ruby 1.8, converting nil generates a TypeError.
fork - Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.
format format(format_string [, arguments...] ) - "Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:"
getc() - obsolete
gets gets(separator=$/) - Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If multiple filenames are present in ARGV, +gets(nil)+ will read the contents one file at a time.
global_variables - Returns an array of the names of global variables.
gsub! gsub!(pattern, replacement) - Equivalent to Kernel::gsub, except nil is returned if $_ is not modified.
gsub gsub(pattern, replacement) - Equivalent to $_.gsub..., except that $_ receives the modified result.
Integer Integer(arg) - Converts arg to a Fixnum or Bignum. Numeric types are converted directly (with floating point numbers being truncated). If arg is a String, leading radix indicators (0, 0b, and 0x) are honored. Others are converted using to_int and to_i. This behavior is different from that of String#to_i.
iterator? - Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.
lambda - Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
load load(filename, wrap=false) - Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program's global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.
local_variables - Returns the names of the current local variables.
loop - Repeatedly executes the block.
method_missing(symbol [, *args] ) - Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.
open open(path [, mode [, perm]] ) - Creates an IO object connected to the given stream, file, or subprocess.
p p(obj, ...) - For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.
pretty_inspect() - returns a pretty printed object as a string.
print print(obj, ...) - Prints each object in turn to $stdout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method.
printf printf(io, string [, obj ... ] ) - "Equivalent to:"
proc - Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
putc putc(int) - "Equivalent to:"
puts puts(obj, ...) - Equivalent to
raise raise - With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
rand rand(max=0) - Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.
readline readline(separator=$/) - Equivalent to Kernel::gets, except readline raises EOFError at end of file.
readlines readlines(separator=$/) - Returns an array containing the lines returned by calling Kernel.gets(separator) until the end of file.
require require(string) - Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ``.rb'', it is loaded as a source file; if the extension is ``.so'', ``.o'', or ``.dll'', or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ``.rb'', ``.so'', and so on to the name. The name of the loaded feature is added to the array in $". A feature will not be loaded if it's name already appears in $". However, the file name is not converted to an absolute path, so that ``require 'a';require './a''' will load a.rb twice.
scan scan(pattern) - Equivalent to calling $_.scan. See String#scan.
select(read_array - See Kernel#select.
set_trace_func set_trace_func(proc) - "Establishes proc as the handler for tracing, or disables tracing if the parameter is nil. proc takes up to six parameters: an event name, a filename, a line number, an object id, a binding, and the name of a class. proc is invoked whenever an event occurs. Events are: c-call (call a C-language routine), c-return (return from a C-language routine), call (call a Ruby method), class (start a class or module definition), end (finish a class or module definition), line (execute code on a new line), raise (raise an exception), and return (return from a Ruby method). Tracing is disabled within the context of proc."
sleep sleep([duration]) - Suspends the current thread for duration seconds (which may be any number, including a Float with fractional seconds). Returns the actual number of seconds slept (rounded), which may be less than that asked for if another thread calls Thread#run. Zero arguments causes sleep to sleep forever.
split split([pattern [, limit]]) - Equivalent to $_.split(pattern, limit). See String#split.
sprintf format(format_string [, arguments...] ) - "Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:"
srand srand(number=0) - Seeds the pseudorandom number generator to the value of number.to_i.abs. If number is omitted, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.
String String(arg) - Converts arg to a String by calling its to_s method.
sub! sub!(pattern, replacement) - Equivalent to $_.sub!(args).
sub sub(pattern, replacement) - Equivalent to $_.sub(args), except that $_ will be updated if substitution occurs.
syscall syscall(fixnum [, args...]) - Calls the operating system function identified by fixnum, passing in the arguments, which must be either String objects, or Integer objects that ultimately fit within a native long. Up to nine parameters may be passed (14 on the Atari-ST). The function identified by fixnum is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h.
system system(cmd [, arg, ...]) - Executes cmd in a subshell, returning true if the command was found and ran successfully, false otherwise. An error status is available in $?. The arguments are processed in the same way as for Kernel::exec.
test test(int_cmd, file1 [, file2] ) - " Uses the integer aCmd to perform various tests on\n file1 (first table below) or on file1 and\n file2 (second table).\n\n File tests on a single file:\n\n Test Returns Meaning\n ?A | Time | Last access time for file1\n ?b | boolean | True if file1 is a block device\n ?c | boolean | True if file1 is a character device\n ?C | Time | Last change time for file1\n ?d | boolean | True if file1 exists and is a directory\n ?e | boolean | True if file1 exists\n ?f | boolean | True if file1 exists and is a regular file\n ?g | boolean | True if file1 has the \\CF{setgid} bit\n | | set (false under NT)\n ?G | boolean | True if file1 exists and has a group\n | | ownership equal to the caller's group\n ?k | boolean | True if file1 exists and has the sticky bit set\n ?l | boolean | True if file1 exists and is a symbolic link\n ?M | Time | Last modification time for file1\n ?o | boolean | True if file1 exists and is owned by\n | | the caller's effective uid\n ?O | boolean | True if file1 exists and is owned by\n | | the caller's real uid\n ?p | boolean | True if file1 exists and is a fifo\n ?r | boolean | True if file1 is readable by the effective\n | | uid/gid of the caller\n ?R | boolean | True if file is readable by the real\n | | uid/gid of the caller\n ?s | int/nil | If file1 has nonzero size, return the size,\n | | otherwise return nil\n ?S | boolean | True if file1 exists and is a socket\n ?u | boolean | True if file1 has the setuid bit set\n ?w | boolean | True if file1 exists and is writable by\n | | the effective uid/gid\n ?W | boolean | True if file1 exists and is writable by\n | | the real uid/gid\n ?x | boolean | True if file1 exists and is executable by\n | | the effective uid/gid\n ?X | boolean | True if file1 exists and is executable by\n | | the real uid/gid\n ?z | boolean | True if file1 exists and has a zero length\n"
throw throw(symbol [, obj]) - Transfers control to the end of the active catch block waiting for symbol. Raises NameError if there is no catch block for the symbol. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.
trace_var trace_var(symbol, cmd ) - Controls tracing of assignments to global variables. The parameter +symbol_ identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc object) or block is executed whenever the variable is assigned. The block or Proc object receives the variable's new value as a parameter. Also see Kernel::untrace_var.
trap( signal, proc ) - Specifies the handling of signals. The first parameter is a signal name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a signal number. The characters ``SIG'' may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string ``IGNORE'' or ``SIG_IGN'', the signal will be ignored. If the command is ``DEFAULT'' or ``SIG_DFL'', the operating system's default handler will be invoked. If the command is ``EXIT'', the script will be terminated by the signal. Otherwise, the given command or block will be run. The special signal name ``EXIT'' or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.
untrace_var untrace_var(symbol [, cmd] ) - Removes tracing for the specified command on the given global variable and returns nil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.
URI(uri_str) - alias for URI.parse.
warn(msg) -