Module: Kernel
- Included in:
- Object
- Defined in:
- object.c,
object.c
Overview
The Kernel module is included by class Object, so its methods are available in every Ruby object.
The Kernel instance methods are documented in class Object while the module methods are documented here. These methods are called without a receiver and thus can be called in functional form:
sprintf "%.1f", 1.234 #=> "1.2"
What’s Here
Module Kernel provides methods that are useful for:
Converting
-
#Array: Returns an Array based on the given argument.
-
#Complex: Returns a Complex based on the given arguments.
-
#Float: Returns a Float based on the given arguments.
-
#Hash: Returns a Hash based on the given argument.
-
#Integer: Returns an Integer based on the given arguments.
-
#Rational: Returns a Rational based on the given arguments.
-
#String: Returns a String based on the given argument.
Querying
-
#__callee__: Returns the called name of the current method as a symbol.
-
#__dir__: Returns the path to the directory from which the current method is called.
-
#__method__: Returns the name of the current method as a symbol.
-
#autoload?: Returns the file to be loaded when the given module is referenced.
-
#binding: Returns a Binding for the context at the point of call.
-
#block_given?: Returns
true
if a block was passed to the calling method. -
#caller: Returns the current execution stack as an array of strings.
-
#caller_locations: Returns the current execution stack as an array of Thread::Backtrace::Location objects.
-
#class: Returns the class of
self
. -
#frozen?: Returns whether
self
is frozen. -
#global_variables: Returns an array of global variables as symbols.
-
#local_variables: Returns an array of local variables as symbols.
-
#test: Performs specified tests on the given single file or pair of files.
Exiting
-
#abort: Exits the current process after printing the given arguments.
-
#at_exit: Executes the given block when the process exits.
-
#exit: Exits the current process after calling any registered
at_exit
handlers. -
#exit!: Exits the current process without calling any registered
at_exit
handlers.
Exceptions
-
#catch: Executes the given block, possibly catching a thrown object.
-
#raise (aliased as #fail): Raises an exception based on the given arguments.
-
#throw: Returns from the active catch block waiting for the given tag.
IO
-
::pp: Prints the given objects in pretty form.
-
#gets: Returns and assigns to
$_
the next line from the current input. -
#open: Creates an IO object connected to the given stream, file, or subprocess.
-
#p: Prints the given objects’ inspect output to the standard output.
-
#print: Prints the given objects to standard output without a newline.
-
#printf: Prints the string resulting from applying the given format string to any additional arguments.
-
#putc: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
-
#puts: Equivalent to
$stdout.puts(*objects)
for the given objects. -
#readline: Similar to #gets, but raises an exception at the end of file.
-
#readlines: Returns an array of the remaining lines from the current input.
-
#select: Same as IO.select.
Procs
-
#lambda: Returns a lambda proc for the given block.
-
#proc: Returns a new Proc; equivalent to Proc.new.
Tracing
-
#set_trace_func: Sets the given proc as the handler for tracing, or disables tracing if given
nil
. -
#trace_var: Starts tracing assignments to the given global variable.
-
#untrace_var: Disables tracing of assignments to the given global variable.
Subprocesses
-
`command`: Returns the standard output of running
command
in a subshell. -
#exec: Replaces current process with a new process.
-
#fork: Forks the current process into two processes.
-
#spawn: Executes the given command and returns its pid without waiting for completion.
-
#system: Executes the given command in a subshell.
Loading
-
#autoload: Registers the given file to be loaded when the given constant is first referenced.
-
#load: Loads the given Ruby file.
-
#require: Loads the given Ruby file unless it has already been loaded.
-
#require_relative: Loads the Ruby file path relative to the calling file, unless it has already been loaded.
Yielding
-
#tap: Yields
self
to the given block; returnsself
. -
#then (aliased as #yield_self): Yields
self
to the block and returns the result of the block.
Random Values
-
#rand: Returns a pseudo-random floating point number strictly between 0.0 and 1.0.
-
#srand: Seeds the pseudo-random number generator with the given number.
Other
-
#eval: Evaluates the given string as Ruby code.
-
#loop: Repeatedly executes the given block.
-
#sleep: Suspends the current thread for the given number of seconds.
-
#sprintf (aliased as #format): Returns the string resulting from applying the given format string to any additional arguments.
-
#syscall: Runs an operating system call.
-
#trap: Specifies the handling of system signals.
-
#warn: Issue a warning based on the given messages and options.
Instance Method Summary collapse
-
#__callee__ ⇒ Object
Returns the called name of the current method as a Symbol.
-
#__dir__ ⇒ String
Returns the canonicalized absolute path of the directory of the file from which this method is called.
-
#__method__ ⇒ Object
Returns the name at the definition of the current method as a Symbol.
-
#` ⇒ String
Returns the
$stdout
output from runningcommand
in a subshell; sets global variable$?
to the process status. -
#abort(*a, _) ⇒ Object
Terminates execution immediately, effectively by calling
Kernel.exit(false)
. -
#Array(object) ⇒ Object
Returns an array converted from
object
. -
#at_exit { ... } ⇒ Proc
Converts block to a
Proc
object (and therefore binds it at the point of call) and registers it for execution when the program exits. -
#autoload(const, filename) ⇒ nil
Registers filename to be loaded (using Kernel::require) the first time that const (which may be a String or a symbol) is accessed.
-
#autoload?(name, inherit = true) ⇒ String?
Returns filename to be loaded if name is registered as
autoload
. -
#binding ⇒ Binding
Returns a Binding object, describing the variable and method bindings at the point of call.
-
#block_given? ⇒ Boolean
Returns
true
ifyield
would execute a block in the current context. -
#callcc {|cont| ... } ⇒ Object
Generates a Continuation object, which it passes to the associated block.
-
#caller(*args) ⇒ Object
Returns the current execution stack—an array containing strings in the form
file:line
orfile:line: in `method'
. -
#caller_locations(*args) ⇒ Object
Returns the current execution stack—an array containing backtrace location objects.
-
#catch([tag]) {|tag| ... } ⇒ Object
catch
executes its block. -
#Complex(*args) ⇒ Object
Returns a new Complex object if the arguments are valid; otherwise raises an exception if
exception
istrue
; otherwise returnsnil
. -
#eval(string[, binding [, filename [,lineno]]]) ⇒ Object
Evaluates the Ruby expression(s) in string.
-
#exec(*a, _) ⇒ Object
Replaces the current process by doing one of the following:.
-
#exit(*a, _) ⇒ Object
Initiates termination of the Ruby script by raising SystemExit; the exception may be caught.
-
#exit!(*args) ⇒ Object
Exits the process immediately; no exit handlers are called.
-
#fail(*v, _) ⇒ Object
With no arguments, raises the exception in
$!
or raises a RuntimeError if$!
isnil
. -
#fork ⇒ Object
Creates a child process.
-
#sprintf(format_string*objects) ⇒ String
Returns the string resulting from formatting
objects
intoformat_string
. -
#gets(*args) ⇒ Object
Returns (and assigns to
$_
) the next line from the list of files inARGV
(or$*
), or from standard input if no files are present on the command line. -
#global_variables ⇒ Array
Returns an array of the names of global variables.
-
#Hash(object) ⇒ Object
Returns a hash converted from
object
. -
#iterator? ⇒ Boolean
Deprecated.
-
#lambda {|...| ... } ⇒ Proc
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
-
#load(filename, wrap = false) ⇒ true
Loads and executes the Ruby program in the file filename.
-
#local_variables ⇒ Array
Returns the names of the current local variables.
-
#open(*args) ⇒ Object
Creates an IO object connected to the given file.
-
#p(*args) ⇒ Object
For each object
obj
, executes:. -
#print(*objects) ⇒ nil
Equivalent to
$stdout.print(*objects)
, this method is the straightforward way to write to$stdout
. -
#printf(*args) ⇒ Object
Equivalent to:.
-
#proc {|...| ... } ⇒ Proc
Equivalent to Proc.new.
-
#putc(int) ⇒ Integer
Equivalent to:.
-
#puts(*objects) ⇒ nil
Equivalent to.
-
#raise(*v, _) ⇒ Object
With no arguments, raises the exception in
$!
or raises a RuntimeError if$!
isnil
. -
#rand(max = 0) ⇒ Numeric
If called without an argument, or if
max.to_i.abs == 0
, rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0. -
#Rational(*args) ⇒ Object
Returns
x/y
orarg
as a Rational. -
#readline(*args) ⇒ Object
Equivalent to method Kernel#gets, except that it raises an exception if called at end-of-stream:.
-
#readlines(*args) ⇒ Object
Returns an array containing the lines returned by calling Kernel#gets until the end-of-stream is reached; (see Line IO).
-
#require(name) ⇒ Boolean
Loads the given
name
, returningtrue
if successful andfalse
if the feature is already loaded. -
#require_relative(string) ⇒ Boolean
Ruby tries to load the library named string relative to the directory containing the requiring file.
-
#select(read_ios, write_ios = [], error_ios = [], timeout = nil) ⇒ Array?
Invokes system call select(2), which monitors multiple file descriptors, waiting until one or more of the file descriptors becomes ready for some class of I/O operation.
-
#set_trace_func(trace) ⇒ Object
Establishes proc as the handler for tracing, or disables tracing if the parameter is
nil
. -
#sleep(secs = nil) ⇒ Object
Suspends execution of the current thread for the number of seconds specified by numeric argument
secs
, or forever ifsecs
isnil
; returns the integer number of seconds suspended (rounded). -
#spawn(*args) ⇒ Object
Creates a new child process by doing one of the following in that process:.
-
#sprintf(format_string*objects) ⇒ String
Returns the string resulting from formatting
objects
intoformat_string
. -
#srand(number = Random.new_seed) ⇒ Object
Seeds the system pseudo-random number generator, with
number
. -
#String(object) ⇒ Object
Returns a string converted from
object
. -
#syscall(integer_callno, *arguments) ⇒ Integer
Invokes Posix system call syscall(2), which calls a specified function.
-
#system(*args) ⇒ Object
Creates a new child process by doing one of the following in that process:.
-
#test(cmd, file1[, file2]) ⇒ Object
Uses the character
cmd
to perform various tests onfile1
(first table below) or onfile1
andfile2
(second table). -
#throw(tag[, obj]) ⇒ Object
Transfers control to the end of the active
catch
block waiting for tag. -
#trace_var(*a, _) ⇒ Object
Controls tracing of assignments to global variables.
-
#trap(*args) ⇒ Object
Specifies the handling of signals.
-
#untrace_var(symbol[, cmd]) ⇒ Array?
Removes tracing for the specified command on the given global variable and returns
nil
.
Instance Method Details
#__callee__ ⇒ Object
Returns the called name of the current method as a Symbol. If called outside of a method, it returns nil
.
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 |
# File 'eval.c', line 1966
static VALUE
rb_f_callee_name(VALUE _)
{
ID fname = prev_frame_callee(); /* need *callee* ID */
if (fname) {
return ID2SYM(fname);
}
else {
return Qnil;
}
}
|
#__dir__ ⇒ String
Returns the canonicalized absolute path of the directory of the file from which this method is called. It means symlinks in the path is resolved. If __FILE__
is nil
, it returns nil
. The return value equals to File.dirname(File.realpath(__FILE__))
.
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 |
# File 'eval.c', line 1989
static VALUE
f_current_dirname(VALUE _)
{
VALUE base = rb_current_realfilepath();
if (NIL_P(base)) {
return Qnil;
}
base = rb_file_dirname(base);
return base;
}
|
#__method__ ⇒ Object
Returns the name at the definition of the current method as a Symbol. If called outside of a method, it returns nil
.
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 |
# File 'eval.c', line 1944
static VALUE
rb_f_method_name(VALUE _)
{
ID fname = prev_frame_func(); /* need *method* ID */
if (fname) {
return ID2SYM(fname);
}
else {
return Qnil;
}
}
|
#` ⇒ String
Returns the $stdout
output from running command
in a subshell; sets global variable $?
to the process status.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
Examples:
$ `date` # => "Wed Apr 9 08:56:30 CDT 2003\n"
$ `echo oops && exit 99` # => "oops\n"
$ $? # => #<Process::Status: pid 17088 exit 99>
$ $?.status # => 99>
The built-in syntax %x{...}
uses this method.
10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 |
# File 'io.c', line 10584
static VALUE
rb_f_backquote(VALUE obj, VALUE str)
{
VALUE port;
VALUE result;
rb_io_t *fptr;
SafeStringValue(str);
rb_last_status_clear();
port = pipe_open_s(str, "r", FMODE_READABLE|DEFAULT_TEXTMODE, NULL);
if (NIL_P(port)) return rb_str_new(0,0);
GetOpenFile(port, fptr);
result = read_all(fptr, remain_size(fptr), Qnil);
rb_io_close(port);
rb_io_fptr_cleanup_all(fptr);
RB_GC_GUARD(port);
return result;
}
|
#abort ⇒ Object #abort(msg = nil) ⇒ Object
Terminates execution immediately, effectively by calling Kernel.exit(false)
.
If string argument msg
is given, it is written to STDERR prior to termination; otherwise, if an exception was raised, prints its message and backtrace.
4576 4577 4578 4579 4580 4581 |
# File 'process.c', line 4576
static VALUE
f_abort(int c, const VALUE *a, VALUE _)
{
rb_f_abort(c, a);
UNREACHABLE_RETURN(Qnil);
}
|
#Array(object) ⇒ Object
Returns an array converted from object
.
Tries to convert object
to an array using to_ary
first and to_a
second:
Array([0, 1, 2]) # => [0, 1, 2]
Array({foo: 0, bar: 1}) # => [[:foo, 0], [:bar, 1]]
Array(0..4) # => [0, 1, 2, 3, 4]
Returns object
in an array, [object]
, if object
cannot be converted:
Array(:foo) # => [:foo]
3824 3825 3826 3827 3828 |
# File 'object.c', line 3824
static VALUE
rb_f_array(VALUE obj, VALUE arg)
{
return rb_Array(arg);
}
|
#at_exit { ... } ⇒ Proc
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.
def do_at_exit(str1)
at_exit { print str1 }
end
at_exit { puts "cruel world" }
do_at_exit("goodbye ")
exit
produces:
goodbye cruel world
37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'eval_jump.c', line 37
static VALUE
rb_f_at_exit(VALUE _)
{
VALUE proc;
if (!rb_block_given_p()) {
rb_raise(rb_eArgError, "called without a block");
}
proc = rb_block_proc();
rb_set_end_proc(rb_call_end_proc, proc);
return proc;
}
|
#autoload(const, filename) ⇒ nil
Registers filename to be loaded (using Kernel::require) the first time that const (which may be a String or a symbol) is accessed.
autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
If const is defined as autoload, the file name to be loaded is replaced with filename. If const is defined but not as autoload, does nothing.
1517 1518 1519 1520 1521 1522 1523 1524 1525 |
# File 'load.c', line 1517
static VALUE
rb_f_autoload(VALUE obj, VALUE sym, VALUE file)
{
VALUE klass = rb_class_real(rb_vm_cbase());
if (!klass) {
rb_raise(rb_eTypeError, "Can not set autoload on singleton class");
}
return rb_mod_autoload(klass, sym, file);
}
|
#autoload?(name, inherit = true) ⇒ String?
Returns filename to be loaded if name is registered as autoload
.
autoload(:B, "b")
autoload?(:B) #=> "b"
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 |
# File 'load.c', line 1538
static VALUE
rb_f_autoload_p(int argc, VALUE *argv, VALUE obj)
{
/* use rb_vm_cbase() as same as rb_f_autoload. */
VALUE klass = rb_vm_cbase();
if (NIL_P(klass)) {
return Qnil;
}
return rb_mod_autoload_p(argc, argv, klass);
}
|
#binding ⇒ Binding
Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling Binding#eval to execute the evaluated command in this environment, or extracting its local variables.
class User
def initialize(name, position)
@name = name
@position = position
end
def get_binding
binding
end
end
user = User.new('Joan', 'manager')
template = '{name: @name, position: @position}'
# evaluate template in context of the object
eval(template, user.get_binding)
#=> {:name=>"Joan", :position=>"manager"}
Binding#local_variable_get can be used to access the variables whose names are reserved Ruby keywords:
# This is valid parameter declaration, but `if` parameter can't
# be accessed by name, because it is a reserved word.
def validate(field, validation, if: nil)
condition = binding.local_variable_get('if')
return unless condition
# ...Some implementation ...
end
validate(:name, :empty?, if: false) # skips validation
validate(:name, :empty?, if: true) # performs validation
374 375 376 377 378 |
# File 'proc.c', line 374
static VALUE
rb_f_binding(VALUE self)
{
return rb_binding_new();
}
|
#block_given? ⇒ Boolean
Returns true
if yield
would execute a block in the current context. The iterator?
form is mildly deprecated.
def try
if block_given?
yield
else
"no block"
end
end
try #=> "no block"
try { "hello" } #=> "hello"
try do "hello" end #=> "hello"
2503 2504 2505 2506 2507 2508 2509 2510 2511 |
# File 'vm_eval.c', line 2503
static VALUE
rb_f_block_given_p(VALUE _)
{
rb_execution_context_t *ec = GET_EC();
rb_control_frame_t *cfp = ec->cfp;
cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp));
return RBOOL(cfp != NULL && VM_CF_BLOCK_HANDLER(cfp) != VM_BLOCK_HANDLER_NONE);
}
|
#callcc {|cont| ... } ⇒ Object
Generates a Continuation object, which it passes to the associated block. You need to require 'continuation'
before using this method. 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.
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 |
# File 'cont.c', line 1765
static VALUE
rb_callcc(VALUE self)
{
volatile int called;
volatile VALUE val = cont_capture(&called);
if (called) {
return val;
}
else {
return rb_yield(val);
}
}
|
#caller(start = 1, length = nil) ⇒ Array? #caller(range) ⇒ Array?
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 top of the stack.
A second optional length
parameter can be used to limit how many entries are returned from the stack.
Returns nil
if start is greater than the size of current execution stack.
Optionally you can pass a range, which will return an array containing the entries within the specified range.
def a(skip)
caller(skip)
end
def b(skip)
a(skip)
end
def c(skip)
b(skip)
end
c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10:in `<main>'"]
c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11:in `<main>'"]
c(2) #=> ["prog:8:in `c'", "prog:12:in `<main>'"]
c(3) #=> ["prog:13:in `<main>'"]
c(4) #=> []
c(5) #=> nil
1232 1233 1234 1235 1236 |
# File 'vm_backtrace.c', line 1232
static VALUE
rb_f_caller(int argc, VALUE *argv, VALUE _)
{
return ec_backtrace_to_ary(GET_EC(), argc, argv, 1, 1, 1);
}
|
#caller_locations(start = 1, length = nil) ⇒ Object #caller_locations(range) ⇒ Object
Returns the current execution stack—an array containing backtrace location objects.
See Thread::Backtrace::Location for more information.
The optional start parameter determines the number of initial stack entries to omit from the top of the stack.
A second optional length
parameter can be used to limit how many entries are returned from the stack.
Returns nil
if start is greater than the size of current execution stack.
Optionally you can pass a range, which will return an array containing the entries within the specified range.
1260 1261 1262 1263 1264 |
# File 'vm_backtrace.c', line 1260
static VALUE
rb_f_caller_locations(int argc, VALUE *argv, VALUE _)
{
return ec_backtrace_to_ary(GET_EC(), argc, argv, 1, 1, 0);
}
|
#catch([tag]) {|tag| ... } ⇒ Object
catch
executes its block. If throw
is not called, the block executes normally, and catch
returns the value of the last expression evaluated.
catch(1) { 123 } # => 123
If throw(tag2, val)
is called, Ruby searches up its stack for a catch
block whose tag
has the same object_id
as tag2. When found, the block stops executing and returns val (or nil
if no second argument was given to throw
).
catch(1) { throw(1, 456) } # => 456
catch(1) { throw(1) } # => nil
When tag
is passed as the first argument, catch
yields it as the parameter of the block.
catch(1) {|x| x + 2 } # => 3
When no tag
is given, catch
yields a new unique object (as from Object.new
) as the block parameter. This object can then be used as the argument to throw
, and will match the correct catch
block.
catch do |obj_A|
catch do |obj_B|
throw(obj_B, 123)
puts "This puts is not reached"
end
puts "This puts is displayed"
456
end
# => 456
catch do |obj_A|
catch do |obj_B|
throw(obj_A, 123)
puts "This puts is still not reached"
end
puts "Now this puts is also not reached"
456
end
# => 123
2341 2342 2343 2344 2345 2346 |
# File 'vm_eval.c', line 2341
static VALUE
rb_f_catch(int argc, VALUE *argv, VALUE self)
{
VALUE tag = rb_check_arity(argc, 0, 1) ? argv[0] : rb_obj_alloc(rb_cObject);
return rb_catch_obj(tag, catch_i, 0);
}
|
#Complex(real, imag = 0, exception: true) ⇒ nil #Complex(s, exception: true) ⇒ nil
Returns a new Complex object if the arguments are valid; otherwise raises an exception if exception
is true
; otherwise returns nil
.
With Numeric arguments real
and imag
, returns Complex.rect(real, imag)
if the arguments are valid.
With string argument s
, returns a new Complex object if the argument is valid; the string may have:
-
One or two numeric substrings, each of which specifies a Complex, Float, Integer, Numeric, or Rational value, specifying rectangular coordinates:
-
Sign-separated real and imaginary numeric substrings (with trailing character
'i'
):Complex('1+2i') # => (1+2i) Complex('+1+2i') # => (1+2i) Complex('+1-2i') # => (1-2i) Complex('-1+2i') # => (-1+2i) Complex('-1-2i') # => (-1-2i)
-
Real-only numeric string (without trailing character
'i'
):Complex('1') # => (1+0i) Complex('+1') # => (1+0i) Complex('-1') # => (-1+0i)
-
Imaginary-only numeric string (with trailing character
'i'
):Complex('1i') # => (0+1i) Complex('+1i') # => (0+1i) Complex('-1i') # => (0-1i)
-
-
At-sign separated real and imaginary rational substrings, each of which specifies a Rational value, specifying polar coordinates:
Complex('1/2@3/4') # => (0.36584443443691045+0.34081938001166706i) Complex('+1/2@+3/4') # => (0.36584443443691045+0.34081938001166706i) Complex('+1/2@-3/4') # => (0.36584443443691045-0.34081938001166706i) Complex('-1/2@+3/4') # => (-0.36584443443691045-0.34081938001166706i) Complex('-1/2@-3/4') # => (-0.36584443443691045+0.34081938001166706i)
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 |
# File 'complex.c', line 576
static VALUE
nucomp_f_complex(int argc, VALUE *argv, VALUE klass)
{
VALUE a1, a2, opts = Qnil;
int raise = TRUE;
if (rb_scan_args(argc, argv, "11:", &a1, &a2, &opts) == 1) {
a2 = Qundef;
}
if (!NIL_P(opts)) {
raise = rb_opts_exception_p(opts, raise);
}
if (argc > 0 && CLASS_OF(a1) == rb_cComplex && UNDEF_P(a2)) {
return a1;
}
return nucomp_convert(rb_cComplex, a1, a2, raise);
}
|
#eval(string[, binding [, filename [,lineno]]]) ⇒ Object
Evaluates the Ruby expression(s) in string. If binding is given, which must be a Binding object, the evaluation is performed in its context. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.
def get_binding(str)
return binding
end
str = "hello"
eval "str + ' Fred'" #=> "hello Fred"
eval "str + ' Fred'", get_binding("bye") #=> "bye Fred"
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 |
# File 'vm_eval.c', line 1782
VALUE
rb_f_eval(int argc, const VALUE *argv, VALUE self)
{
VALUE src, scope, vfile, vline;
VALUE file = Qundef;
int line = 1;
rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
SafeStringValue(src);
if (argc >= 3) {
StringValue(vfile);
}
if (argc >= 4) {
line = NUM2INT(vline);
}
if (!NIL_P(vfile))
file = vfile;
if (NIL_P(scope))
return eval_string_with_cref(self, src, NULL, file, line);
else
return eval_string_with_scope(scope, src, file, line);
}
|
#exec([env, ], options = {}) ⇒ Object #exec([env, ], *args, options = {}) ⇒ Object
Replaces the current process by doing one of the following:
-
Passing string
command_line
to the shell. -
Invoking the executable at
exe_path
.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
The new process is created using the exec system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).
Argument env
, if given, is a hash that affects ENV
for the new process; see Execution Environment.
Argument options
is a hash of options for the new process; see Execution Options.
The first required argument is one of the following:
-
command_line
if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters. -
exe_path
otherwise.
Argument command_line
String argument command_line
is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:
exec('if true; then echo "Foo"; fi') # Shell reserved word.
exec('echo') # Built-in.
exec('date > date.tmp') # Contains meta character.
The command line may also contain arguments and options for the command:
exec('echo "Foo"')
Output:
Foo
See Execution Shell for details about the shell.
Raises an exception if the new process could not execute.
Argument exe_path
Argument exe_path
is one of the following:
-
The string path to an executable to be called.
-
A 2-element array containing the path to an executable and the string to be used as the name of the executing process.
Example:
exec('/usr/bin/date')
Output:
Sat Aug 26 09:38:00 AM CDT 2023
Ruby invokes the executable directly, with no shell and no shell expansion:
exec('doesnt_exist') # Raises Errno::ENOENT
If one or more args
is given, each is an argument or option to be passed to the executable:
exec('echo', 'C*')
exec('echo', 'hello', 'world')
Output:
C*
hello world
Raises an exception if the new process could not execute.
3134 3135 3136 3137 3138 3139 |
# File 'process.c', line 3134
static VALUE
f_exec(int c, const VALUE *a, VALUE _)
{
rb_f_exec(c, a);
UNREACHABLE_RETURN(Qnil);
}
|
#exit(status = true) ⇒ Object #exit(status = true) ⇒ Object
Initiates termination of the Ruby script by raising SystemExit; the exception may be caught. Returns exit status status
to the underlying operating system.
Values true
and false
for argument status
indicate, respectively, success and failure; The meanings of integer values are system-dependent.
Example:
begin
exit
puts 'Never get here.'
rescue SystemExit
puts 'Rescued a SystemExit exception.'
end
puts 'After begin block.'
Output:
Rescued a SystemExit exception.
After begin block.
Just prior to final termination, Ruby executes any at-exit procedures (see Kernel::at_exit) and any object finalizers (see ObjectSpace::define_finalizer).
Example:
at_exit { puts 'In at_exit function.' }
ObjectSpace.define_finalizer('string', proc { puts 'In finalizer.' })
exit
Output:
In at_exit function.
In finalizer.
4528 4529 4530 4531 4532 4533 |
# File 'process.c', line 4528
static VALUE
f_exit(int c, const VALUE *a, VALUE _)
{
rb_f_exit(c, a);
UNREACHABLE_RETURN(Qnil);
}
|
#exit!(status = false) ⇒ Object #exit!(status = false) ⇒ Object
4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 |
# File 'process.c', line 4437
static VALUE
rb_f_exit_bang(int argc, VALUE *argv, VALUE obj)
{
int istatus;
if (rb_check_arity(argc, 0, 1) == 1) {
istatus = exit_status_code(argv[0]);
}
else {
istatus = EXIT_FAILURE;
}
_exit(istatus);
UNREACHABLE_RETURN(Qnil);
}
|
#raise ⇒ Object #raise(string, cause: $!) ⇒ Object #raise(exception[, string [, array]], cause: $!) ⇒ Object #fail ⇒ Object #fail(string, cause: $!) ⇒ Object #fail(exception[, string [, array]], cause: $!) ⇒ Object
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 an Exception
class (or another object that returns an Exception
object when sent an exception
message). The optional second parameter sets the message associated with the exception (accessible via Exception#message), and the third parameter is an array of callback information (accessible via Exception#backtrace). The cause
of the generated exception (accessible via Exception#cause) is automatically set to the “current” exception ($!
), if any. An alternative value, either an Exception
object or nil
, can be specified via the :cause
argument.
Exceptions are caught by the rescue
clause of begin...end
blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
786 787 788 789 790 |
# File 'eval.c', line 786
static VALUE
f_raise(int c, VALUE *v, VALUE _)
{
return rb_f_raise(c, v);
}
|
#fork { ... } ⇒ Integer? #fork ⇒ Integer?
Creates a child process.
With a block given, runs the block in the child process; on block exit, the child terminates with a status of zero:
puts "Before the fork: #{Process.pid}"
fork do
puts "In the child process: #{Process.pid}"
end # => 382141
puts "After the fork: #{Process.pid}"
Output:
Before the fork: 420496
After the fork: 420496
In the child process: 420520
With no block given, the fork
call returns twice:
-
Once in the parent process, returning the pid of the child process.
-
Once in the child process, returning
nil
.
Example:
puts "This is the first line before the fork (pid #{Process.pid})"
puts fork
puts "This is the second line after the fork (pid #{Process.pid})"
Output:
This is the first line before the fork (pid 420199)
420223
This is the second line after the fork (pid 420199)
This is the second line after the fork (pid 420223)
In either case, the child process may exit using Kernel.exit! to avoid the call to Kernel#at_exit.
To avoid zombie processes, the parent process should call either:
-
Process.wait, to collect the termination statuses of its children.
-
Process.detach, to register disinterest in their status.
The thread calling fork
is the only thread in the created child process; fork
doesn’t copy other threads.
Note that method fork
is available on some platforms, but not on others:
Process.respond_to?(:fork) # => true # Would be false on some.
If not, you may use ::spawn instead of fork
.
4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 |
# File 'process.c', line 4374
static VALUE
rb_f_fork(VALUE obj)
{
rb_pid_t pid;
pid = rb_call_proc__fork();
if (pid == 0) {
if (rb_block_given_p()) {
int status;
rb_protect(rb_yield, Qundef, &status);
ruby_stop(status);
}
return Qnil;
}
return PIDT2NUM(pid);
}
|
#sprintf(format_string*objects) ⇒ String
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
3954 3955 3956 3957 3958 |
# File 'object.c', line 3954
static VALUE
f_sprintf(int c, const VALUE *v, VALUE _)
{
return rb_f_sprintf(c, v);
}
|
#gets(sep = $/[, getline_args]) ⇒ String? #gets(limit[, getline_args]) ⇒ String? #gets(sep, limit[, getline_args]) ⇒ String?
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 the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present in ARGV
, gets(nil)
will read the contents one file at a time.
ARGV << "testfile"
print while gets
produces:
This is line one
This is line two
This is line three
And so on...
The style of programming using $_
as an implicit parameter is gradually losing favor in the Ruby community.
10327 10328 10329 10330 10331 10332 10333 10334 |
# File 'io.c', line 10327
static VALUE
rb_f_gets(int argc, VALUE *argv, VALUE recv)
{
if (recv == argf) {
return argf_gets(argc, argv, argf);
}
return forward(argf, idGets, argc, argv);
}
|
#global_variables ⇒ Array
Returns an array of the names of global variables. This includes special regexp global variables such as $~
and $+
, but does not include the numbered regexp global variables ($1
, $2
, etc.).
global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
2012 2013 2014 2015 2016 |
# File 'eval.c', line 2012
static VALUE
f_global_variables(VALUE _)
{
return rb_f_global_variables();
}
|
#Hash(object) ⇒ Object
Returns a hash converted from object
.
-
If
object
is:-
A hash, returns
object
. -
An empty array or
nil
, returns an empty hash.
-
-
Otherwise, if
object.to_hash
returns a hash, returns that hash. -
Otherwise, returns TypeError.
Examples:
Hash({foo: 0, bar: 1}) # => {:foo=>0, :bar=>1}
Hash(nil) # => {}
Hash([]) # => {}
3870 3871 3872 3873 3874 |
# File 'object.c', line 3870
static VALUE
rb_f_hash(VALUE obj, VALUE arg)
{
return rb_Hash(arg);
}
|
#iterator? ⇒ Boolean
Deprecated. Use block_given? instead.
2520 2521 2522 2523 2524 2525 |
# File 'vm_eval.c', line 2520
static VALUE
rb_f_iterator_p(VALUE self)
{
rb_warn_deprecated("iterator?", "block_given?");
return rb_f_block_given_p(self);
}
|
#lambda {|...| ... } ⇒ Proc
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
894 895 896 897 898 899 |
# File 'proc.c', line 894
static VALUE
f_lambda(VALUE _)
{
f_lambda_filter_non_literal();
return rb_block_lambda();
}
|
#load(filename, wrap = false) ⇒ true
Loads and executes the Ruby program in the file filename.
If the filename is an absolute path (e.g. starts with ‘/’), the file will be loaded directly using the absolute path.
If the filename is an explicit relative path (e.g. starts with ‘./’ or ‘../’), the file will be loaded using the relative path from the current directory.
Otherwise, the file will be searched for in the library directories listed in $LOAD_PATH
($:
). If the file is found in a directory, it will attempt to load the file relative to that directory. If the file is not found in any of the directories in $LOAD_PATH
, the file will be loaded using the relative path from the current directory.
If the file doesn’t exist when there is an attempt to load it, a LoadError will be raised.
If the optional wrap parameter is true
, the loaded script will be executed under an anonymous module, protecting the calling program’s global namespace. If the optional wrap parameter is a module, the loaded script will be executed under the given module. In no circumstance will any local variables in the loaded file be propagated to the loading environment.
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
# File 'load.c', line 893
static VALUE
rb_f_load(int argc, VALUE *argv, VALUE _)
{
VALUE fname, wrap, path, orig_fname;
rb_scan_args(argc, argv, "11", &fname, &wrap);
orig_fname = rb_get_path_check_to_string(fname);
fname = rb_str_encode_ospath(orig_fname);
RUBY_DTRACE_HOOK(LOAD_ENTRY, RSTRING_PTR(orig_fname));
path = rb_find_file(fname);
if (!path) {
if (!rb_file_load_ok(RSTRING_PTR(fname)))
load_failed(orig_fname);
path = fname;
}
rb_load_internal(path, wrap);
RUBY_DTRACE_HOOK(LOAD_RETURN, RSTRING_PTR(orig_fname));
return Qtrue;
}
|
#local_variables ⇒ Array
Returns the names of the current local variables.
fred = 1
for i in 1..10
# ...
end
local_variables #=> [:fred, :i]
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 |
# File 'vm_eval.c', line 2448
static VALUE
rb_f_local_variables(VALUE _)
{
struct local_var_list vars;
rb_execution_context_t *ec = GET_EC();
rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp));
unsigned int i;
local_var_list_init(&vars);
while (cfp) {
if (cfp->iseq) {
for (i = 0; i < ISEQ_BODY(cfp->iseq)->local_table_size; i++) {
local_var_list_add(&vars, ISEQ_BODY(cfp->iseq)->local_table[i]);
}
}
if (!VM_ENV_LOCAL_P(cfp->ep)) {
/* block */
const VALUE *ep = VM_CF_PREV_EP(cfp);
if (vm_collect_local_variables_in_heap(ep, &vars)) {
break;
}
else {
while (cfp->ep != ep) {
cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
}
}
}
else {
break;
}
}
return local_var_list_finish(&vars);
}
|
#open(path, mode = 'r', perm = 0666, **opts) ⇒ IO? #open(path, mode = 'r', perm = 0666, **opts) {|io| ... } ⇒ Object
Creates an IO object connected to the given file.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
With no block given, file stream is returned:
open('t.txt') # => #<File:t.txt>
With a block given, calls the block with the open file stream, then closes the stream:
open('t.txt') {|f| p f } # => #<File:t.txt (closed)>
Output:
#<File:t.txt>
See File.open for details.
8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 |
# File 'io.c', line 8246
static VALUE
rb_f_open(int argc, VALUE *argv, VALUE _)
{
ID to_open = 0;
int redirect = FALSE;
if (argc >= 1) {
CONST_ID(to_open, "to_open");
if (rb_respond_to(argv[0], to_open)) {
redirect = TRUE;
}
else {
VALUE tmp = argv[0];
FilePathValue(tmp);
if (NIL_P(tmp)) {
redirect = TRUE;
}
else {
VALUE cmd = check_pipe_command(tmp);
if (!NIL_P(cmd)) {
// TODO: when removed in 4.0, update command_injection.rdoc
rb_warn_deprecated_to_remove_at(4.0, "Calling Kernel#open with a leading '|'", "IO.popen");
argv[0] = cmd;
return rb_io_s_popen(argc, argv, rb_cIO);
}
}
}
}
if (redirect) {
VALUE io = rb_funcallv_kw(argv[0], to_open, argc-1, argv+1, RB_PASS_CALLED_KEYWORDS);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, io, io_close, io);
}
return io;
}
return rb_io_s_open(argc, argv, rb_cFile);
}
|
#p(object) ⇒ Object #p(*objects) ⇒ Object #p ⇒ nil
For each object obj
, executes:
$stdout.write(obj.inspect, "\n")
With one object given, returns the object; with multiple objects given, returns an array containing the objects; with no object given, returns nil
.
Examples:
r = Range.new(0, 4)
p r # => 0..4
p [r, r, r] # => [0..4, 0..4, 0..4]
p # => nil
Output:
0..4
[0..4, 0..4, 0..4]
Kernel#p is designed for debugging purposes. Ruby implementations may define Kernel#p to be uninterruptible in whole or in part. On CRuby, Kernel#p’s writing of data is uninterruptible.
9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 |
# File 'io.c', line 9078
static VALUE
rb_f_p(int argc, VALUE *argv, VALUE self)
{
int i;
for (i=0; i<argc; i++) {
VALUE inspected = rb_obj_as_string(rb_inspect(argv[i]));
rb_uninterruptible(rb_p_write, inspected);
}
return rb_p_result(argc, argv);
}
|
#print(*objects) ⇒ nil
Equivalent to $stdout.print(*objects)
, this method is the straightforward way to write to $stdout
.
Writes the given objects to $stdout
; returns nil
. Appends the output record separator $OUTPUT_RECORD_SEPARATOR
$\
), if it is not nil
.
With argument objects
given, for each object:
-
Converts via its method
to_s
if not a string. -
Writes to
stdout
. -
If not the last object, writes the output field separator
$OUTPUT_FIELD_SEPARATOR
($,
if it is notnil
.
With default separators:
objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero']
$OUTPUT_RECORD_SEPARATOR
$OUTPUT_FIELD_SEPARATOR
print(*objects)
Output:
nil
nil
00.00/10+0izerozero
With specified separators:
$OUTPUT_RECORD_SEPARATOR = "\n"
$OUTPUT_FIELD_SEPARATOR = ','
print(*objects)
Output:
0,0.0,0/1,0+0i,zero,zero
With no argument given, writes the content of $_
(which is usually the most recent user input):
gets # Sets $_ to the most recent user input.
print # Prints $_.
8791 8792 8793 8794 8795 8796 |
# File 'io.c', line 8791
static VALUE
rb_f_print(int argc, const VALUE *argv, VALUE _)
{
rb_io_print(argc, argv, rb_ractor_stdout());
return Qnil;
}
|
#printf(format_string, *objects) ⇒ nil #printf(io, format_string, *objects) ⇒ nil
Equivalent to:
io.write(sprintf(format_string, *objects))
For details on format_string
, see Format Specifications.
With the single argument format_string
, formats objects
into the string, then writes the formatted string to $stdout:
printf('%4.4d %10s %2.2f', 24, 24, 24.0)
Output (on $stdout):
0024 24 24.00#
With arguments io
and format_string
, formats objects
into the string, then writes the formatted string to io
:
printf($stderr, '%4.4d %10s %2.2f', 24, 24, 24.0)
Output (on $stderr):
0024 24 24.00# => nil
With no arguments, does nothing.
8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 |
# File 'io.c', line 8629
static VALUE
rb_f_printf(int argc, VALUE *argv, VALUE _)
{
VALUE out;
if (argc == 0) return Qnil;
if (RB_TYPE_P(argv[0], T_STRING)) {
out = rb_ractor_stdout();
}
else {
out = argv[0];
argv++;
argc--;
}
rb_io_write(out, rb_f_sprintf(argc, argv));
return Qnil;
}
|
#proc {|...| ... } ⇒ Proc
Equivalent to Proc.new.
843 844 845 846 847 |
# File 'proc.c', line 843
static VALUE
f_proc(VALUE _)
{
return proc_new(rb_cProc, FALSE);
}
|
#putc(int) ⇒ Integer
Equivalent to:
$stdout.putc(int)
See IO#putc for important information regarding multi-byte characters.
8853 8854 8855 8856 8857 8858 8859 8860 8861 |
# File 'io.c', line 8853
static VALUE
rb_f_putc(VALUE recv, VALUE ch)
{
VALUE r_stdout = rb_ractor_stdout();
if (recv == r_stdout) {
return rb_io_putc(recv, ch);
}
return forward(r_stdout, rb_intern("putc"), 1, &ch);
}
|
#puts(*objects) ⇒ nil
Equivalent to
$stdout.puts(objects)
8995 8996 8997 8998 8999 9000 9001 9002 9003 |
# File 'io.c', line 8995
static VALUE
rb_f_puts(int argc, VALUE *argv, VALUE recv)
{
VALUE r_stdout = rb_ractor_stdout();
if (recv == r_stdout) {
return rb_io_puts(argc, argv, recv);
}
return forward(r_stdout, rb_intern("puts"), argc, argv);
}
|
#raise ⇒ Object #raise(string, cause: $!) ⇒ Object #raise(exception[, string [, array]], cause: $!) ⇒ Object #fail ⇒ Object #fail(string, cause: $!) ⇒ Object #fail(exception[, string [, array]], cause: $!) ⇒ Object
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 an Exception
class (or another object that returns an Exception
object when sent an exception
message). The optional second parameter sets the message associated with the exception (accessible via Exception#message), and the third parameter is an array of callback information (accessible via Exception#backtrace). The cause
of the generated exception (accessible via Exception#cause) is automatically set to the “current” exception ($!
), if any. An alternative value, either an Exception
object or nil
, can be specified via the :cause
argument.
Exceptions are caught by the rescue
clause of begin...end
blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
786 787 788 789 790 |
# File 'eval.c', line 786
static VALUE
f_raise(int c, VALUE *v, VALUE _)
{
return rb_f_raise(c, v);
}
|
#rand(max = 0) ⇒ Numeric
If called without an argument, or if max.to_i.abs == 0
, rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0.
rand #=> 0.2725926052826416
When max.abs
is greater than or equal to 1, rand
returns a pseudo-random integer greater than or equal to 0 and less than max.to_i.abs
.
rand(100) #=> 12
When max
is a Range, rand
returns a random number where range.member?(number) == true
.
Negative or floating point values for max
are allowed, but may give surprising results.
rand(-100) # => 87
rand(-0.5) # => 0.8130921818028143
rand(1.9) # equivalent to rand(1), which is always 0
Kernel.srand may be used to ensure that sequences of random numbers are reproducible between different runs of a program.
See also Random.rand.
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 |
# File 'random.c', line 1667
static VALUE
rb_f_rand(int argc, VALUE *argv, VALUE obj)
{
VALUE vmax;
rb_random_t *rnd = rand_start(default_rand());
if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
VALUE v = rand_range(obj, rnd, vmax);
if (v != Qfalse) return v;
vmax = rb_to_int(vmax);
if (vmax != INT2FIX(0)) {
v = rand_int(obj, rnd, vmax, 0);
if (!NIL_P(v)) return v;
}
}
return DBL2NUM(random_real(obj, rnd, TRUE));
}
|
#Rational(x, y, exception: true) ⇒ nil #Rational(arg, exception: true) ⇒ nil
Returns x/y
or arg
as a Rational.
Rational(2, 3) #=> (2/3)
Rational(5) #=> (5/1)
Rational(0.5) #=> (1/2)
Rational(0.3) #=> (5404319552844595/18014398509481984)
Rational("2/3") #=> (2/3)
Rational("0.3") #=> (3/10)
Rational("10 cents") #=> ArgumentError
Rational(nil) #=> TypeError
Rational(1, nil) #=> TypeError
Rational("10 cents", exception: false) #=> nil
Syntax of the string form:
string form = extra spaces , rational , extra spaces ;
rational = [ sign ] , unsigned rational ;
unsigned rational = numerator | numerator , "/" , denominator ;
numerator = integer part | fractional part | integer part , fractional part ;
denominator = digits ;
integer part = digits ;
fractional part = "." , digits , [ ( "e" | "E" ) , [ sign ] , digits ] ;
sign = "-" | "+" ;
digits = digit , { digit | "_" , digit } ;
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
extra spaces = ? \s* ? ;
See also String#to_r.
553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
# File 'rational.c', line 553
static VALUE
nurat_f_rational(int argc, VALUE *argv, VALUE klass)
{
VALUE a1, a2, opts = Qnil;
int raise = TRUE;
if (rb_scan_args(argc, argv, "11:", &a1, &a2, &opts) == 1) {
a2 = Qundef;
}
if (!NIL_P(opts)) {
raise = rb_opts_exception_p(opts, raise);
}
return nurat_convert(rb_cRational, a1, a2, raise);
}
|
#readline(sep = $/, chomp: false) ⇒ String #readline(limit, chomp: false) ⇒ String #readline(sep, limit, chomp: false) ⇒ String
Equivalent to method Kernel#gets, except that it raises an exception if called at end-of-stream:
$ cat t.txt | ruby -e "p readlines; readline"
["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
in `readline': end of file reached (EOFError)
Optional keyword argument chomp
specifies whether line separators are to be omitted.
10410 10411 10412 10413 10414 10415 10416 10417 |
# File 'io.c', line 10410
static VALUE
rb_f_readline(int argc, VALUE *argv, VALUE recv)
{
if (recv == argf) {
return argf_readline(argc, argv, argf);
}
return forward(argf, rb_intern("readline"), argc, argv);
}
|
#readlines(sep = $/, chomp: false, **enc_opts) ⇒ Array #readlines(limit, chomp: false, **enc_opts) ⇒ Array #readlines(sep, limit, chomp: false, **enc_opts) ⇒ Array
Returns an array containing the lines returned by calling Kernel#gets until the end-of-stream is reached; (see Line IO).
With only string argument sep
given, returns the remaining lines as determined by line separator sep
, or nil
if none; see Line Separator:
# Default separator.
$ cat t.txt | ruby -e "p readlines"
["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
# Specified separator.
$ cat t.txt | ruby -e "p readlines 'li'"
["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
# Get-all separator.
$ cat t.txt | ruby -e "p readlines nil"
["First line\nSecond line\n\nFourth line\nFifth line\n"]
# Get-paragraph separator.
$ cat t.txt | ruby -e "p readlines ''"
["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
With only integer argument limit
given, limits the number of bytes in the line; see Line Limit:
$cat t.txt | ruby -e "p readlines 10"
["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"]
$cat t.txt | ruby -e "p readlines 11"
["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"]
$cat t.txt | ruby -e "p readlines 12"
["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
With arguments sep
and limit
given, combines the two behaviors; see Line Separator and Line Limit.
Optional keyword argument chomp
specifies whether line separators are to be omitted:
$ cat t.txt | ruby -e "p readlines(chomp: true)"
["First line", "Second line", "", "Fourth line", "Fifth line"]
Optional keyword arguments enc_opts
specify encoding options; see Encoding options.
10512 10513 10514 10515 10516 10517 10518 10519 |
# File 'io.c', line 10512
static VALUE
rb_f_readlines(int argc, VALUE *argv, VALUE recv)
{
if (recv == argf) {
return argf_readlines(argc, argv, argf);
}
return forward(argf, rb_intern("readlines"), argc, argv);
}
|
#require(name) ⇒ Boolean
Loads the given name
, returning true
if successful and false
if the feature is already loaded.
If the filename neither resolves to an absolute path nor starts with ‘./’ or ‘../’, the file will be searched for in the library directories listed in $LOAD_PATH
($:
). If the filename starts with ‘./’ or ‘../’, resolution is based on Dir.pwd.
If the filename has the extension “.rb”, it is loaded as a source file; if the extension is “.so”, “.o”, or the default shared library extension 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 until found. If the file named cannot be found, a LoadError will be raised.
For Ruby extensions the filename given may use “.so” or “.o”. For example, on macOS the socket extension is “socket.bundle” and require 'socket.so'
will load the socket extension.
The absolute path of the loaded file is added to $LOADED_FEATURES
($"
). A file will not be loaded again if its path already appears in $"
. For example, require 'a'; require './a'
will not load a.rb
again.
require "my-library.rb"
require "db-driver"
Any constants or globals within the loaded source file will be available in the calling program’s global namespace. However, local variables will not be propagated to the loading environment.
1012 1013 1014 1015 1016 |
# File 'load.c', line 1012
VALUE
rb_f_require(VALUE obj, VALUE fname)
{
return rb_require_string(fname);
}
|
#require_relative(string) ⇒ Boolean
Ruby tries to load the library named string relative to the directory containing the requiring file. If the file does not exist a LoadError is raised. Returns true
if the file was loaded and false
if the file was already loaded before.
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 |
# File 'load.c', line 1027
VALUE
rb_f_require_relative(VALUE obj, VALUE fname)
{
VALUE base = rb_current_realfilepath();
if (NIL_P(base)) {
rb_loaderror("cannot infer basepath");
}
base = rb_file_dirname(base);
return rb_require_string_internal(rb_file_absolute_path(fname, base), false);
}
|
#select(read_ios, write_ios = [], error_ios = [], timeout = nil) ⇒ Array?
Invokes system call select(2), which monitors multiple file descriptors, waiting until one or more of the file descriptors becomes ready for some class of I/O operation.
Not implemented on all platforms.
Each of the arguments read_ios
, write_ios
, and error_ios
is an array of IO objects.
Argument timeout
is an integer timeout interval in seconds.
The method monitors the IO objects given in all three arrays, waiting for some to be ready; returns a 3-element array whose elements are:
-
An array of the objects in
read_ios
that are ready for reading. -
An array of the objects in
write_ios
that are ready for writing. -
An array of the objects in
error_ios
have pending exceptions.
If no object becomes ready within the given timeout
, nil
is returned.
IO.select peeks the buffer of IO objects for testing readability. If the IO buffer is not empty, IO.select immediately notifies readability. This “peek” only happens for IO objects. It does not happen for IO-like objects such as OpenSSL::SSL::SSLSocket.
The best way to use IO.select is invoking it after non-blocking methods such as #read_nonblock, #write_nonblock, etc. The methods raise an exception which is extended by IO::WaitReadable or IO::WaitWritable. The modules notify how the caller should wait with IO.select. If IO::WaitReadable is raised, the caller should wait for reading. If IO::WaitWritable is raised, the caller should wait for writing.
So, blocking read (#readpartial) can be emulated using #read_nonblock and IO.select as follows:
begin
result = io_like.read_nonblock(maxlen)
rescue IO::WaitReadable
IO.select([io_like])
retry
rescue IO::WaitWritable
IO.select(nil, [io_like])
retry
end
Especially, the combination of non-blocking methods and IO.select is preferred for IO like objects such as OpenSSL::SSL::SSLSocket. It has #to_io method to return underlying IO object. IO.select calls #to_io to obtain the file descriptor to wait.
This means that readability notified by IO.select doesn’t mean readability from OpenSSL::SSL::SSLSocket object.
The most likely situation is that OpenSSL::SSL::SSLSocket buffers some data. IO.select doesn’t see the buffer. So IO.select can block when OpenSSL::SSL::SSLSocket#readpartial doesn’t block.
However, several more complicated situations exist.
SSL is a protocol which is sequence of records. The record consists of multiple bytes. So, the remote side of SSL sends a partial record, IO.select notifies readability but OpenSSL::SSL::SSLSocket cannot decrypt a byte and OpenSSL::SSL::SSLSocket#readpartial will block.
Also, the remote side can request SSL renegotiation which forces the local SSL engine to write some data. This means OpenSSL::SSL::SSLSocket#readpartial may invoke #write system call and it can block. In such a situation, OpenSSL::SSL::SSLSocket#read_nonblock raises IO::WaitWritable instead of blocking. So, the caller should wait for ready for writability as above example.
The combination of non-blocking methods and IO.select is also useful for streams such as tty, pipe socket socket when multiple processes read from a stream.
Finally, Linux kernel developers don’t guarantee that readability of select(2) means readability of following read(2) even for a single process; see select(2)
Invoking IO.select before IO#readpartial works well as usual. However it is not the best way to use IO.select.
The writability notified by select(2) doesn’t show how many bytes are writable. IO#write method blocks until given whole string is written. So, IO#write(two or more bytes)
can block after writability is notified by IO.select. IO#write_nonblock is required to avoid the blocking.
Blocking write (#write) can be emulated using #write_nonblock and IO.select as follows: IO::WaitReadable should also be rescued for SSL renegotiation in OpenSSL::SSL::SSLSocket.
while 0 < string.bytesize
begin
written = io_like.write_nonblock(string)
rescue IO::WaitReadable
IO.select([io_like])
retry
rescue IO::WaitWritable
IO.select(nil, [io_like])
retry
end
string = string.byteslice(written..-1)
end
Example:
rp, wp = IO.pipe
mesg = "ping "
100.times {
# IO.select follows IO#read. Not the best way to use IO.select.
rs, ws, = IO.select([rp], [wp])
if r = rs[0]
ret = r.read(5)
print ret
case ret
when /ping/
mesg = "pong\n"
when /pong/
mesg = "ping "
end
end
if w = ws[0]
w.write(mesg)
end
}
Output:
ping pong
ping pong
ping pong
(snipped)
ping
11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 |
# File 'io.c', line 11073
static VALUE
rb_f_select(int argc, VALUE *argv, VALUE obj)
{
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
// It's optionally supported.
VALUE result = rb_fiber_scheduler_io_selectv(scheduler, argc, argv);
if (!UNDEF_P(result)) return result;
}
VALUE timeout;
struct select_args args;
struct timeval timerec;
int i;
rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);
if (NIL_P(timeout)) {
args.timeout = 0;
}
else {
timerec = rb_time_interval(timeout);
args.timeout = &timerec;
}
for (i = 0; i < numberof(args.fdsets); ++i)
rb_fd_init(&args.fdsets[i]);
return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args);
}
|
#set_trace_func(proc) ⇒ Proc #set_trace_func(nil) ⇒ nil
Establishes proc as the handler for tracing, or disables tracing if the parameter is nil
.
Note: this method is obsolete, please use TracePoint instead.
proc takes up to six parameters:
-
an event name string
-
a filename string
-
a line number
-
a method name symbol, or nil
-
a binding, or nil
-
the class, module, or nil
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
"return"
-
return from a Ruby method
Tracing is disabled within the context of proc.
class Test
def test
a = 1
b = 2
end
end
set_trace_func proc { |event, file, line, id, binding, class_or_module|
printf "%8s %s:%-2d %16p %14p\n", event, file, line, id, class_or_module
}
t = Test.new
t.test
Produces:
c-return prog.rb:8 :set_trace_func Kernel
line prog.rb:11 nil nil
c-call prog.rb:11 :new Class
c-call prog.rb:11 :initialize BasicObject
c-return prog.rb:11 :initialize BasicObject
c-return prog.rb:11 :new Class
line prog.rb:12 nil nil
call prog.rb:2 :test Test
line prog.rb:3 :test Test
line prog.rb:4 :test Test
return prog.rb:5 :test Test
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
# File 'vm_trace.c', line 578
static VALUE
set_trace_func(VALUE obj, VALUE trace)
{
rb_remove_event_hook(call_trace_func);
if (NIL_P(trace)) {
return Qnil;
}
if (!rb_obj_is_proc(trace)) {
rb_raise(rb_eTypeError, "trace_func needs to be Proc");
}
rb_add_event_hook(call_trace_func, RUBY_EVENT_ALL, trace);
return trace;
}
|
#sleep(secs = nil) ⇒ Object
Suspends execution of the current thread for the number of seconds specified by numeric argument secs
, or forever if secs
is nil
; returns the integer number of seconds suspended (rounded).
Time.new # => 2008-03-08 19:56:19 +0900
sleep 1.2 # => 1
Time.new # => 2008-03-08 19:56:20 +0900
sleep 1.9 # => 2
Time.new # => 2008-03-08 19:56:22 +0900
5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 |
# File 'process.c', line 5054
static VALUE
rb_f_sleep(int argc, VALUE *argv, VALUE _)
{
time_t beg = time(0);
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
rb_fiber_scheduler_kernel_sleepv(scheduler, argc, argv);
}
else {
if (argc == 0 || (argc == 1 && NIL_P(argv[0]))) {
rb_thread_sleep_forever();
}
else {
rb_check_arity(argc, 0, 1);
rb_thread_wait_for(rb_time_interval(argv[0]));
}
}
time_t end = time(0) - beg;
return TIMET2NUM(end);
}
|
#spawn([env, ], options = {}) ⇒ Object #spawn([env, ], *args, options = {}) ⇒ Object
Creates a new child process by doing one of the following in that process:
-
Passing string
command_line
to the shell. -
Invoking the executable at
exe_path
.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
Returns the process ID (pid) of the new process, without waiting for it to complete.
To avoid zombie processes, the parent process should call either:
-
Process.wait, to collect the termination statuses of its children.
-
Process.detach, to register disinterest in their status.
The new process is created using the exec system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).
Argument env
, if given, is a hash that affects ENV
for the new process; see Execution Environment.
Argument options
is a hash of options for the new process; see Execution Options.
The first required argument is one of the following:
-
command_line
if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters. -
exe_path
otherwise.
Argument command_line
String argument command_line
is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:
spawn('if true; then echo "Foo"; fi') # => 798847 # Shell reserved word.
Process.wait # => 798847
spawn('echo') # => 798848 # Built-in.
Process.wait # => 798848
spawn('date > /tmp/date.tmp') # => 798879 # Contains meta character.
Process.wait # => 798849
spawn('date > /nop/date.tmp') # => 798882 # Issues error message.
Process.wait # => 798882
The command line may also contain arguments and options for the command:
spawn('echo "Foo"') # => 799031
Process.wait # => 799031
Output:
Foo
See Execution Shell for details about the shell.
Raises an exception if the new process could not execute.
Argument exe_path
Argument exe_path
is one of the following:
-
The string path to an executable to be called:
spawn('/usr/bin/date') # Path to date on Unix-style system. Process.wait
Output:
Thu Aug 31 10:06:48 AM CDT 2023
-
A 2-element array containing the path to an executable and the string to be used as the name of the executing process:
pid = spawn(['sleep', 'Hello!'], '1') # 2-element array. p `ps -p #{pid} -o command=`
Output:
"Hello! 1\n"
Ruby invokes the executable directly, with no shell and no shell expansion.
If one or more args
is given, each is an argument or option to be passed to the executable:
spawn('echo', 'C*') # => 799392
Process.wait # => 799392
spawn('echo', 'hello', 'world') # => 799393
Process.wait # => 799393
Output:
C*
hello world
Raises an exception if the new process could not execute.
5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 |
# File 'process.c', line 5011
static VALUE
rb_f_spawn(int argc, VALUE *argv, VALUE _)
{
rb_pid_t pid;
char errmsg[CHILD_ERRMSG_BUFLEN] = { '\0' };
VALUE execarg_obj, fail_str;
struct rb_execarg *eargp;
execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
eargp = rb_execarg_get(execarg_obj);
fail_str = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
pid = rb_execarg_spawn(execarg_obj, errmsg, sizeof(errmsg));
if (pid == -1) {
int err = errno;
rb_exec_fail(eargp, err, errmsg);
RB_GC_GUARD(execarg_obj);
rb_syserr_fail_str(err, fail_str);
}
#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
return PIDT2NUM(pid);
#else
return Qnil;
#endif
}
|
#sprintf(format_string*objects) ⇒ String
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
3954 3955 3956 3957 3958 |
# File 'object.c', line 3954
static VALUE
f_sprintf(int c, const VALUE *v, VALUE _)
{
return rb_f_sprintf(c, v);
}
|
#srand(number = Random.new_seed) ⇒ Object
Seeds the system pseudo-random number generator, with number
. The previous seed value is returned.
If number
is omitted, seeds the generator using a source of entropy provided by the operating system, if available (/dev/urandom on Unix systems or the RSA cryptographic provider on Windows), which is then combined with the time, the process id, and a sequence number.
srand may be used to ensure repeatable sequences of pseudo-random numbers between different runs of the program. By setting the seed to a known value, programs can be made deterministic during testing.
srand 1234 # => 268519324636777531569100071560086917274
[ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
[ rand(10), rand(1000) ] # => [4, 664]
srand 1234 # => 1234
[ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 |
# File 'random.c', line 953
static VALUE
rb_f_srand(int argc, VALUE *argv, VALUE obj)
{
VALUE seed, old;
rb_random_mt_t *r = rand_mt_start(default_rand());
if (rb_check_arity(argc, 0, 1) == 0) {
seed = random_seed(obj);
}
else {
seed = rb_to_int(argv[0]);
}
old = r->base.seed;
rand_init(&random_mt_if, &r->base, seed);
r->base.seed = seed;
return old;
}
|
#String(object) ⇒ Object
Returns a string converted from object
.
Tries to convert object
to a string using to_str
first and to_s
second:
String([0, 1, 2]) # => "[0, 1, 2]"
String(0..5) # => "0..5"
String({foo: 0, bar: 1}) # => "{:foo=>0, :bar=>1}"
Raises TypeError
if object
cannot be converted to a string.
3784 3785 3786 3787 3788 |
# File 'object.c', line 3784
static VALUE
rb_f_string(VALUE obj, VALUE arg)
{
return rb_String(arg);
}
|
#syscall(integer_callno, *arguments) ⇒ Integer
Invokes Posix system call syscall(2), which calls a specified function.
Calls the operating system function identified by integer_callno
; returns the result of the function or raises SystemCallError if it failed. The effect of the call is platform-dependent. The arguments and returned value are platform-dependent.
For each of arguments
: if it is an integer, it is passed directly; if it is a string, it is interpreted as a binary sequence of bytes. There may be as many as nine such arguments.
Arguments integer_callno
and argument
, as well as the returned value, are platform-dependent.
Note: Method syscall
is essentially unsafe and unportable. The DL (Fiddle) library is preferred for safer and a bit more portable programming.
Not implemented on all platforms.
11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 |
# File 'io.c', line 11548
static VALUE
rb_f_syscall(int argc, VALUE *argv, VALUE _)
{
VALUE arg[8];
#if SIZEOF_VOIDP == 8 && defined(HAVE___SYSCALL) && SIZEOF_INT != 8 /* mainly *BSD */
# define SYSCALL __syscall
# define NUM2SYSCALLID(x) NUM2LONG(x)
# define RETVAL2NUM(x) LONG2NUM(x)
# if SIZEOF_LONG == 8
long num, retval = -1;
# elif SIZEOF_LONG_LONG == 8
long long num, retval = -1;
# else
# error ---->> it is asserted that __syscall takes the first argument and returns retval in 64bit signed integer. <<----
# endif
#elif defined(__linux__)
# define SYSCALL syscall
# define NUM2SYSCALLID(x) NUM2LONG(x)
# define RETVAL2NUM(x) LONG2NUM(x)
/*
* Linux man page says, syscall(2) function prototype is below.
*
* int syscall(int number, ...);
*
* But, it's incorrect. Actual one takes and returned long. (see unistd.h)
*/
long num, retval = -1;
#else
# define SYSCALL syscall
# define NUM2SYSCALLID(x) NUM2INT(x)
# define RETVAL2NUM(x) INT2NUM(x)
int num, retval = -1;
#endif
int i;
if (RTEST(ruby_verbose)) {
rb_category_warning(RB_WARN_CATEGORY_DEPRECATED,
"We plan to remove a syscall function at future release. DL(Fiddle) provides safer alternative.");
}
if (argc == 0)
rb_raise(rb_eArgError, "too few arguments for syscall");
if (argc > numberof(arg))
rb_raise(rb_eArgError, "too many arguments for syscall");
num = NUM2SYSCALLID(argv[0]); ++argv;
for (i = argc - 1; i--; ) {
VALUE v = rb_check_string_type(argv[i]);
if (!NIL_P(v)) {
SafeStringValue(v);
rb_str_modify(v);
arg[i] = (VALUE)StringValueCStr(v);
}
else {
arg[i] = (VALUE)NUM2LONG(argv[i]);
}
}
switch (argc) {
case 1:
retval = SYSCALL(num);
break;
case 2:
retval = SYSCALL(num, arg[0]);
break;
case 3:
retval = SYSCALL(num, arg[0],arg[1]);
break;
case 4:
retval = SYSCALL(num, arg[0],arg[1],arg[2]);
break;
case 5:
retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]);
break;
case 6:
retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]);
break;
case 7:
retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
break;
case 8:
retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
break;
}
if (retval == -1)
rb_sys_fail(0);
return RETVAL2NUM(retval);
#undef SYSCALL
#undef NUM2SYSCALLID
#undef RETVAL2NUM
}
|
#system([env, ], options = {}, exception: false) ⇒ true, ... #system([env, ], *args, options = {}, exception: false) ⇒ true, ...
Creates a new child process by doing one of the following in that process:
-
Passing string
command_line
to the shell. -
Invoking the executable at
exe_path
.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
Returns:
-
true
if the command exits with status zero. -
false
if the exit status is a non-zero integer. -
nil
if the command could not execute.
Raises an exception (instead of returning false
or nil
) if keyword argument exception
is set to true
.
Assigns the command’s error status to $?
.
The new process is created using the system system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).
Argument env
, if given, is a hash that affects ENV
for the new process; see Execution Environment.
Argument options
is a hash of options for the new process; see Execution Options.
The first required argument is one of the following:
-
command_line
if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters. -
exe_path
otherwise.
Argument command_line
String argument command_line
is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:
system('if true; then echo "Foo"; fi') # => true # Shell reserved word.
system('echo') # => true # Built-in.
system('date > /tmp/date.tmp') # => true # Contains meta character.
system('date > /nop/date.tmp') # => false
system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
Assigns the command’s error status to $?
:
system('echo') # => true # Built-in.
$? # => #<Process::Status: pid 640610 exit 0>
system('date > /nop/date.tmp') # => false
$? # => #<Process::Status: pid 640742 exit 2>
The command line may also contain arguments and options for the command:
system('echo "Foo"') # => true
Output:
Foo
See Execution Shell for details about the shell.
Raises an exception if the new process could not execute.
Argument exe_path
Argument exe_path
is one of the following:
-
The string path to an executable to be called.
-
A 2-element array containing the path to an executable and the string to be used as the name of the executing process.
Example:
system('/usr/bin/date') # => true # Path to date on Unix-style system.
system('foo') # => nil # Command failed.
Output:
Mon Aug 28 11:43:10 AM CDT 2023
Assigns the command’s error status to $?
:
system('/usr/bin/date') # => true
$? # => #<Process::Status: pid 645605 exit 0>
system('foo') # => nil
$? # => #<Process::Status: pid 645608 exit 127>
Ruby invokes the executable directly, with no shell and no shell expansion:
system('doesnt_exist') # => nil
If one or more args
is given, each is an argument or option to be passed to the executable:
system('echo', 'C*') # => true
system('echo', 'hello', 'world') # => true
Output:
C*
hello world
Raises an exception if the new process could not execute.
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 |
# File 'process.c', line 4840
static VALUE
rb_f_system(int argc, VALUE *argv, VALUE _)
{
rb_thread_t *th = GET_THREAD();
VALUE execarg_obj = rb_execarg_new(argc, argv, TRUE, TRUE);
struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
struct rb_process_status status = {0};
eargp->status = &status;
last_status_clear(th);
// This function can set the thread's last status.
// May be different from waitpid_state.pid on exec failure.
rb_pid_t pid = rb_execarg_spawn(execarg_obj, 0, 0);
if (pid > 0) {
VALUE status = rb_process_status_wait(pid, 0);
struct rb_process_status *data = rb_check_typeddata(status, &rb_process_status_type);
// Set the last status:
rb_obj_freeze(status);
th->last_status = status;
if (data->status == EXIT_SUCCESS) {
return Qtrue;
}
if (data->error != 0) {
if (eargp->exception) {
VALUE command = eargp->invoke.sh.shell_script;
RB_GC_GUARD(execarg_obj);
rb_syserr_fail_str(data->error, command);
}
else {
return Qnil;
}
}
else if (eargp->exception) {
VALUE command = eargp->invoke.sh.shell_script;
VALUE str = rb_str_new_cstr("Command failed with");
rb_str_cat_cstr(pst_message_status(str, data->status), ": ");
rb_str_append(str, command);
RB_GC_GUARD(execarg_obj);
rb_exc_raise(rb_exc_new_str(rb_eRuntimeError, str));
}
else {
return Qfalse;
}
RB_GC_GUARD(status);
}
if (eargp->exception) {
VALUE command = eargp->invoke.sh.shell_script;
RB_GC_GUARD(execarg_obj);
rb_syserr_fail_str(errno, command);
}
else {
return Qnil;
}
}
|
#test(cmd, file1[, file2]) ⇒ Object
Uses the character cmd
to perform various tests on file1
(first table below) or on file1
and file2
(second table).
File tests on a single file:
Cmd Returns Meaning
"A" | Time | Last access time for file1
"b" | boolean | True if file1 is a block device
"c" | boolean | True if file1 is a character device
"C" | Time | Last change time for file1
"d" | boolean | True if file1 exists and is a directory
"e" | boolean | True if file1 exists
"f" | boolean | True if file1 exists and is a regular file
"g" | boolean | True if file1 has the setgid bit set
"G" | boolean | True if file1 exists and has a group
| | ownership equal to the caller's group
"k" | boolean | True if file1 exists and has the sticky bit set
"l" | boolean | True if file1 exists and is a symbolic link
"M" | Time | Last modification time for file1
"o" | boolean | True if file1 exists and is owned by
| | the caller's effective uid
"O" | boolean | True if file1 exists and is owned by
| | the caller's real uid
"p" | boolean | True if file1 exists and is a fifo
"r" | boolean | True if file1 is readable by the effective
| | uid/gid of the caller
"R" | boolean | True if file is readable by the real
| | uid/gid of the caller
"s" | int/nil | If file1 has nonzero size, return the size,
| | otherwise return nil
"S" | boolean | True if file1 exists and is a socket
"u" | boolean | True if file1 has the setuid bit set
"w" | boolean | True if file1 exists and is writable by
| | the effective uid/gid
"W" | boolean | True if file1 exists and is writable by
| | the real uid/gid
"x" | boolean | True if file1 exists and is executable by
| | the effective uid/gid
"X" | boolean | True if file1 exists and is executable by
| | the real uid/gid
"z" | boolean | True if file1 exists and has a zero length
Tests that take two files:
"-" | boolean | True if file1 and file2 are identical
"=" | boolean | True if the modification times of file1
| | and file2 are equal
"<" | boolean | True if the modification time of file1
| | is prior to that of file2
">" | boolean | True if the modification time of file1
| | is after that of file2
5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 |
# File 'file.c', line 5413
static VALUE
rb_f_test(int argc, VALUE *argv, VALUE _)
{
int cmd;
if (argc == 0) rb_check_arity(argc, 2, 3);
cmd = NUM2CHR(argv[0]);
if (cmd == 0) {
goto unknown;
}
if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
CHECK(1);
switch (cmd) {
case 'b':
return rb_file_blockdev_p(0, argv[1]);
case 'c':
return rb_file_chardev_p(0, argv[1]);
case 'd':
return rb_file_directory_p(0, argv[1]);
case 'e':
return rb_file_exist_p(0, argv[1]);
case 'f':
return rb_file_file_p(0, argv[1]);
case 'g':
return rb_file_sgid_p(0, argv[1]);
case 'G':
return rb_file_grpowned_p(0, argv[1]);
case 'k':
return rb_file_sticky_p(0, argv[1]);
case 'l':
return rb_file_symlink_p(0, argv[1]);
case 'o':
return rb_file_owned_p(0, argv[1]);
case 'O':
return rb_file_rowned_p(0, argv[1]);
case 'p':
return rb_file_pipe_p(0, argv[1]);
case 'r':
return rb_file_readable_p(0, argv[1]);
case 'R':
return rb_file_readable_real_p(0, argv[1]);
case 's':
return rb_file_size_p(0, argv[1]);
case 'S':
return rb_file_socket_p(0, argv[1]);
case 'u':
return rb_file_suid_p(0, argv[1]);
case 'w':
return rb_file_writable_p(0, argv[1]);
case 'W':
return rb_file_writable_real_p(0, argv[1]);
case 'x':
return rb_file_executable_p(0, argv[1]);
case 'X':
return rb_file_executable_real_p(0, argv[1]);
case 'z':
return rb_file_zero_p(0, argv[1]);
}
}
if (strchr("MAC", cmd)) {
struct stat st;
VALUE fname = argv[1];
CHECK(1);
if (rb_stat(fname, &st) == -1) {
int e = errno;
FilePathValue(fname);
rb_syserr_fail_path(e, fname);
}
switch (cmd) {
case 'A':
return stat_atime(&st);
case 'M':
return stat_mtime(&st);
case 'C':
return stat_ctime(&st);
}
}
if (cmd == '-') {
CHECK(2);
return rb_file_identical_p(0, argv[1], argv[2]);
}
if (strchr("=<>", cmd)) {
struct stat st1, st2;
struct timespec t1, t2;
CHECK(2);
if (rb_stat(argv[1], &st1) < 0) return Qfalse;
if (rb_stat(argv[2], &st2) < 0) return Qfalse;
t1 = stat_mtimespec(&st1);
t2 = stat_mtimespec(&st2);
switch (cmd) {
case '=':
if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue;
return Qfalse;
case '>':
if (t1.tv_sec > t2.tv_sec) return Qtrue;
if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue;
return Qfalse;
case '<':
if (t1.tv_sec < t2.tv_sec) return Qtrue;
if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue;
return Qfalse;
}
}
unknown:
/* unknown command */
if (ISPRINT(cmd)) {
rb_raise(rb_eArgError, "unknown command '%s%c'", cmd == '\'' || cmd == '\\' ? "\\" : "", cmd);
}
else {
rb_raise(rb_eArgError, "unknown command \"\\x%02X\"", cmd);
}
UNREACHABLE_RETURN(Qundef);
}
|
#throw(tag[, obj]) ⇒ Object
Transfers control to the end of the active catch
block waiting for tag. Raises UncaughtThrowError
if there is no catch
block for the tag. The optional second parameter supplies a return value for the catch
block, which otherwise defaults to nil
. For examples, see Kernel::catch.
2243 2244 2245 2246 2247 2248 2249 2250 2251 |
# File 'vm_eval.c', line 2243
static VALUE
rb_f_throw(int argc, VALUE *argv, VALUE _)
{
VALUE tag, value;
rb_scan_args(argc, argv, "11", &tag, &value);
rb_throw_obj(tag, value);
UNREACHABLE_RETURN(Qnil);
}
|
#trace_var(symbol, cmd) ⇒ nil #trace_var(symbol) {|val| ... } ⇒ nil
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.
trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
$_ = "hello"
$_ = ' there'
produces:
$_ is now 'hello'
$_ is now ' there'
2041 2042 2043 2044 2045 |
# File 'eval.c', line 2041
static VALUE
f_trace_var(int c, const VALUE *a, VALUE _)
{
return rb_f_trace_var(c, a);
}
|
#trap(signal, command) ⇒ Object #trap(signal) {|| ... } ⇒ Object
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 Ruby’s default handler will be invoked. If the command is “EXIT”, the script will be terminated by the signal. If the command is “SYSTEM_DEFAULT”, the operating system’s default handler will be invoked. 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.
Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD") { puts "Child died" }
fork && Process.wait
produces:
Terminating: 27461
Child died
Terminating: 27460
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 |
# File 'signal.c', line 1345
static VALUE
sig_trap(int argc, VALUE *argv, VALUE _)
{
int sig;
sighandler_t func;
VALUE cmd;
rb_check_arity(argc, 1, 2);
sig = trap_signm(argv[0]);
if (reserved_signal_p(sig)) {
const char *name = signo2signm(sig);
if (name)
rb_raise(rb_eArgError, "can't trap reserved signal: SIG%s", name);
else
rb_raise(rb_eArgError, "can't trap reserved signal: %d", sig);
}
if (argc == 1) {
cmd = rb_block_proc();
func = sighandler;
}
else {
cmd = argv[1];
func = trap_handler(&cmd, sig);
}
if (rb_obj_is_proc(cmd) &&
!rb_ractor_main_p() && !rb_ractor_shareable_p(cmd)) {
cmd = rb_proc_isolate(cmd);
}
return trap(sig, func, cmd);
}
|
#untrace_var(symbol[, cmd]) ⇒ Array?
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.
2057 2058 2059 2060 2061 |
# File 'eval.c', line 2057
static VALUE
f_untrace_var(int c, const VALUE *a, VALUE _)
{
return rb_f_untrace_var(c, a);
}
|