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"

Instance Method Summary collapse

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.



1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
# File 'eval.c', line 1983

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__)).

Returns:



2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
# File 'eval.c', line 2006

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.



1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
# File 'eval.c', line 1961

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 standard output of running cmd in a subshell. The built-in syntax %x{...} uses this method. Sets $? to the process status.

`date`                   #=> "Wed Apr  9 08:56:30 CDT 2003\n"
`ls testdir`.split[1]    #=> "main.rb"
`echo oops && exit 99`   #=> "oops\n"
$?.exitstatus            #=> 99

Returns:



9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
# File 'io.c', line 9246

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);
    RFILE(port)->fptr = NULL;
    rb_io_fptr_finalize(fptr);
    rb_gc_force_recycle(port); /* also guards from premature GC */

    return result;
}

#abortObject #Kernel::abort([msg]) ⇒ Object #abort([msg]) ⇒ Object

Terminate execution immediately, effectively by calling Kernel.exit(false). If msg is given, it is written to STDERR prior to terminating.



4531
4532
4533
4534
4535
4536
# File 'process.c', line 4531

static VALUE
f_abort(int c, const VALUE *a, VALUE _)
{
    rb_f_abort(c, a);
    UNREACHABLE_RETURN(Qnil);
}

#Array(arg) ⇒ Array

Returns arg as an Array.

First tries to call to_ary on arg, then to_a. If arg does not respond to to_ary or to_a, returns an Array of length 1 containing arg.

If to_ary or to_a returns something other than an Array, raises a TypeError.

Array(["a", "b"])  #=> ["a", "b"]
Array(1..5)        #=> [1, 2, 3, 4, 5]
Array(key: :value) #=> [[:key, :value]]
Array(nil)         #=> []
Array(1)           #=> [1]

Returns:



3954
3955
3956
3957
3958
# File 'object.c', line 3954

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

Yields:

Returns:



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;
}

#autoloadnil

Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")

Returns:

  • (nil)


1259
1260
1261
1262
1263
1264
1265
1266
1267
# File 'load.c', line 1259

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"

Returns:



1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
# File 'load.c', line 1280

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);
}

#bindingBinding

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. See also the description of class Binding.

def get_binding(param)
  binding
end
b = get_binding("hello")
eval("param", b)   #=> "hello"

Returns:



386
387
388
389
390
# File 'proc.c', line 386

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"

Returns:

  • (Boolean)


2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
# File 'vm_eval.c', line 2379

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));

    if (cfp != NULL && VM_CF_BLOCK_HANDLER(cfp) != VM_BLOCK_HANDLER_NONE) {
	return Qtrue;
    }
    else {
	return Qfalse;
    }
}

#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.

Yields:

  • (cont)

Returns:



1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
# File 'cont.c', line 1524

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

Overloads:

  • #caller(start = 1, length = nil) ⇒ Array?

    Returns:

  • #caller(range) ⇒ Array?

    Returns:



1161
1162
1163
1164
1165
# File 'vm_backtrace.c', line 1161

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.



1189
1190
1191
1192
1193
# File 'vm_backtrace.c', line 1189

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

Yields:

  • (tag)

Returns:



2217
2218
2219
2220
2221
2222
# File 'vm_eval.c', line 2217

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(x[, y], exception: true) ⇒ Numeric?

Returns x+i*y;

Complex(1, 2)    #=> (1+2i)
Complex('1+2i')  #=> (1+2i)
Complex(nil)     #=> TypeError
Complex(1, nil)  #=> TypeError

Complex(1, nil, exception: false)  #=> nil
Complex('1+2', exception: false)   #=> nil

Syntax of string form:

string form = extra spaces , complex , extra spaces ;
complex = real part | [ sign ] , imaginary part
        | real part , sign , imaginary part
        | rational , "@" , rational ;
real part = rational ;
imaginary part = imaginary unit | unsigned rational , imaginary unit ;
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 ] ;
imaginary unit = "i" | "I" | "j" | "J" ;
sign = "-" | "+" ;
digits = digit , { digit | "_" , digit };
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
extra spaces = ? \s* ? ;

See String#to_c.

Returns:



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'complex.c', line 549

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 && a2 == Qundef) {
        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"

Returns:



1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
# File 'vm_eval.c', line 1617

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

Replaces the current process by running the given external command, which can take one of the following forms:

exec(commandline)

command line string which is passed to the standard shell

exec(cmdname, arg1, ...)

command name and one or more arguments (no shell)

exec([cmdname, argv0], arg1, ...)

command name, argv and zero or more arguments (no shell)

In the first form, the string is taken as a command line that is subject to shell expansion before being executed.

The standard shell always means "/bin/sh" on Unix-like systems, same as ENV["RUBYSHELL"] (or ENV["COMSPEC"] on Windows NT series), and similar.

If the string from the first form (exec("command")) follows these simple rules:

  • no meta characters

  • no shell reserved word and no special built-in

  • Ruby invokes the command directly without shell

You can force shell invocation by adding “;” to the string (because “;” is a meta character).

Note that this behavior is observable by pid obtained (return value of spawn() and IO#pid for IO.popen) is the pid of the invoked command, not shell.

In the second form (exec("command1", "arg1", ...)), the first is taken as a command name and the rest are passed as parameters to command with no shell expansion.

In the third form (exec(["command", "argv0"], "arg1", ...)), starting a two-element array at the beginning of the command, 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 order to execute the command, one of the exec(2) system calls are used, so the running command may inherit some of the environment of the original program (including open file descriptors).

This behavior is modified by the given env and options parameters. See ::spawn for details.

If the command fails to execute (typically Errno::ENOENT when it was not found) a SystemCallError exception is raised.

This method modifies process attributes according to given options before exec(2) system call. See ::spawn for more details about the given options.

The modified attributes may be retained when exec(2) system call fails.

For example, hard resource limits are not restorable.

Consider to create a child process using ::spawn or Kernel#system if this is not acceptable.

exec "echo *"       # echoes list of files in current directory
# never get here

exec "echo", "*"    # echoes an asterisk
# never get here


3215
3216
3217
3218
3219
3220
# File 'process.c', line 3215

static VALUE
f_exec(int c, const VALUE *a, VALUE _)
{
    rb_f_exec(c, a);
    UNREACHABLE_RETURN(Qnil);
}

#exit(status = true) ⇒ Object #Kernel::exit(status = true) ⇒ Object #Process::exit(status = true) ⇒ Object

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. true and FALSE of status means success and failure respectively. The interpretation of other integer values are system dependent.

begin
  exit
  puts "never get here"
rescue SystemExit
  puts "rescued a SystemExit exception"
end
puts "after begin block"

produces:

rescued a SystemExit exception
after begin block

Just prior to termination, Ruby executes any at_exit functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer).

at_exit { puts "at_exit function" }
ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
exit

produces:

at_exit function
in finalizer


4486
4487
4488
4489
4490
4491
# File 'process.c', line 4486

static VALUE
f_exit(int c, const VALUE *a, VALUE _)
{
    rb_f_exit(c, a);
    UNREACHABLE_RETURN(Qnil);
}

#exit!(status = false) ⇒ Object

Exits the process immediately. No exit handlers are run. status is returned to the underlying system as the exit status.

Process.exit!(true)


4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
# File 'process.c', line 4399

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);
}

#raiseObject #raise(string, cause: $!) ⇒ Object #raise(exception[, string [, array]], cause: $!) ⇒ Object #failObject #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


821
822
823
824
825
# File 'eval.c', line 821

static VALUE
f_raise(int c, VALUE *v, VALUE _)
{
    return rb_f_raise(c, v);
}

#fork { ... } ⇒ Integer? #fork { ... } ⇒ Integer?

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.

The thread calling fork is the only thread in the created child process. fork doesn’t copy other threads.

If fork is not usable, Process.respond_to?(:fork) returns false.

Note that fork(2) is not available on some platforms like Windows and NetBSD 4. Therefore you should use spawn() instead of fork().

Overloads:



4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
# File 'process.c', line 4337

static VALUE
rb_f_fork(VALUE obj)
{
    rb_pid_t pid;

    switch (pid = rb_fork_ruby(NULL)) {
      case 0:
	rb_thread_atfork();
	if (rb_block_given_p()) {
	    int status;
	    rb_protect(rb_yield, Qundef, &status);
	    ruby_stop(status);
	}
	return Qnil;

      case -1:
	rb_sys_fail("fork(2)");
	return Qnil;

      default:
	return PIDT2NUM(pid);
    }
}

#format(format_string[, arguments...]) ⇒ String #sprintf(format_string[, arguments...]) ⇒ String

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.

The syntax of a format sequence is as follows.

%[flags][width][.precision]type

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:

Field |  Integer Format
------+--------------------------------------------------------------
  b   | Convert argument as a binary number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..1'.
  B   | Equivalent to `b', but uses an uppercase 0B for prefix
      | in the alternative format by #.
  d   | Convert argument as a decimal number.
  i   | Identical to `d'.
  o   | Convert argument as an octal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..7'.
  u   | Identical to `d'.
  x   | Convert argument as a hexadecimal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..f' (representing an infinite string of
      | leading 'ff's).
  X   | Equivalent to `x', but uses uppercase letters.

Field |  Float Format
------+--------------------------------------------------------------
  e   | Convert floating point argument into exponential notation
      | with one digit before the decimal point as [-]d.dddddde[+-]dd.
      | The precision specifies the number of digits after the decimal
      | point (defaulting to six).
  E   | Equivalent to `e', but uses an uppercase E to indicate
      | the exponent.
  f   | Convert floating point argument as [-]ddd.dddddd,
      | where the precision specifies the number of digits after
      | the decimal point.
  g   | Convert a floating point number using exponential form
      | if the exponent is less than -4 or greater than or
      | equal to the precision, or in dd.dddd form otherwise.
      | The precision specifies the number of significant digits.
  G   | Equivalent to `g', but use an uppercase `E' in exponent form.
  a   | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
      | which is consisted from optional sign, "0x", fraction part
      | as hexadecimal, "p", and exponential part as decimal.
  A   | Equivalent to `a', but use uppercase `X' and `P'.

Field |  Other Format
------+--------------------------------------------------------------
  c   | Argument is the numeric code for a single character or
      | a single character string itself.
  p   | The valuing of argument.inspect.
  s   | Argument is a string to be substituted.  If the format
      | sequence contains a precision, at most that many characters
      | will be copied.
  %   | A percent sign itself will be displayed.  No argument taken.

The flags modifies the behavior of the formats. The flag characters are:

Flag     | Applies to    | Meaning
---------+---------------+-----------------------------------------
space    | bBdiouxX      | Leave a space at the start of
         | aAeEfgG       | non-negative numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
(digit)$ | all           | Specifies the absolute argument number
         |               | for this field.  Absolute and relative
         |               | argument numbers cannot be mixed in a
         |               | sprintf string.
---------+---------------+-----------------------------------------
 #       | bBoxX         | Use an alternative format.
         | aAeEfgG       | For the conversions `o', increase the precision
         |               | until the first digit will be `0' if
         |               | it is not formatted as complements.
         |               | For the conversions `x', `X', `b' and `B'
         |               | on non-zero, prefix the result with ``0x'',
         |               | ``0X'', ``0b'' and ``0B'', respectively.
         |               | For `a', `A', `e', `E', `f', `g', and 'G',
         |               | force a decimal point to be added,
         |               | even if no digits follow.
         |               | For `g' and 'G', do not remove trailing zeros.
---------+---------------+-----------------------------------------
+        | bBdiouxX      | Add a leading plus sign to non-negative
         | aAeEfgG       | numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
-        | all           | Left-justify the result of this conversion.
---------+---------------+-----------------------------------------
0 (zero) | bBdiouxX      | Pad with zeros, not spaces.
         | aAeEfgG       | For `o', `x', `X', `b' and `B', radix-1
         | (numeric fmt) | is used for negative numbers formatted as
         |               | complements.
---------+---------------+-----------------------------------------
*        | all           | Use the next argument as the field width.
         |               | If negative, left-justify the result. If the
         |               | asterisk is followed by a number and a dollar
         |               | sign, use the indicated argument as the width.

Examples of flags:

# `+' and space flag specifies the sign of non-negative numbers.
sprintf("%d", 123)  #=> "123"
sprintf("%+d", 123) #=> "+123"
sprintf("% d", 123) #=> " 123"

# `#' flag for `o' increases number of digits to show `0'.
# `+' and space flag changes format of negative numbers.
sprintf("%o", 123)   #=> "173"
sprintf("%#o", 123)  #=> "0173"
sprintf("%+o", -123) #=> "-173"
sprintf("%o", -123)  #=> "..7605"
sprintf("%#o", -123) #=> "..7605"

# `#' flag for `x' add a prefix `0x' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%x", 123)   #=> "7b"
sprintf("%#x", 123)  #=> "0x7b"
sprintf("%+x", -123) #=> "-7b"
sprintf("%x", -123)  #=> "..f85"
sprintf("%#x", -123) #=> "0x..f85"
sprintf("%#x", 0)    #=> "0"

# `#' for `X' uses the prefix `0X'.
sprintf("%X", 123)  #=> "7B"
sprintf("%#X", 123) #=> "0X7B"

# `#' flag for `b' add a prefix `0b' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%b", 123)   #=> "1111011"
sprintf("%#b", 123)  #=> "0b1111011"
sprintf("%+b", -123) #=> "-1111011"
sprintf("%b", -123)  #=> "..10000101"
sprintf("%#b", -123) #=> "0b..10000101"
sprintf("%#b", 0)    #=> "0"

# `#' for `B' uses the prefix `0B'.
sprintf("%B", 123)  #=> "1111011"
sprintf("%#B", 123) #=> "0B1111011"

# `#' for `e' forces to show the decimal point.
sprintf("%.0e", 1)  #=> "1e+00"
sprintf("%#.0e", 1) #=> "1.e+00"

# `#' for `f' forces to show the decimal point.
sprintf("%.0f", 1234)  #=> "1234"
sprintf("%#.0f", 1234) #=> "1234."

# `#' for `g' forces to show the decimal point.
# It also disables stripping lowest zeros.
sprintf("%g", 123.4)   #=> "123.4"
sprintf("%#g", 123.4)  #=> "123.400"
sprintf("%g", 123456)  #=> "123456"
sprintf("%#g", 123456) #=> "123456."

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Examples of width:

# padding is done by spaces,       width=20
# 0 or radix-1.             <------------------>
sprintf("%20d", 123)   #=> "                 123"
sprintf("%+20d", 123)  #=> "                +123"
sprintf("%020d", 123)  #=> "00000000000000000123"
sprintf("%+020d", 123) #=> "+0000000000000000123"
sprintf("% 020d", 123) #=> " 0000000000000000123"
sprintf("%-20d", 123)  #=> "123                 "
sprintf("%-+20d", 123) #=> "+123                "
sprintf("%- 20d", 123) #=> " 123                "
sprintf("%020x", -123) #=> "..ffffffffffffffff85"

For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

Examples of precisions:

# precision for `d', 'o', 'x' and 'b' is
# minimum number of digits               <------>
sprintf("%20.8d", 123)  #=> "            00000123"
sprintf("%20.8o", 123)  #=> "            00000173"
sprintf("%20.8x", 123)  #=> "            0000007b"
sprintf("%20.8b", 123)  #=> "            01111011"
sprintf("%20.8d", -123) #=> "           -00000123"
sprintf("%20.8o", -123) #=> "            ..777605"
sprintf("%20.8x", -123) #=> "            ..ffff85"
sprintf("%20.8b", -11)  #=> "            ..110101"

# "0x" and "0b" for `#x' and `#b' is not counted for
# precision but "0" for `#o' is counted.  <------>
sprintf("%#20.8d", 123)  #=> "            00000123"
sprintf("%#20.8o", 123)  #=> "            00000173"
sprintf("%#20.8x", 123)  #=> "          0x0000007b"
sprintf("%#20.8b", 123)  #=> "          0b01111011"
sprintf("%#20.8d", -123) #=> "           -00000123"
sprintf("%#20.8o", -123) #=> "            ..777605"
sprintf("%#20.8x", -123) #=> "          0x..ffff85"
sprintf("%#20.8b", -11)  #=> "          0b..110101"

# precision for `e' is number of
# digits after the decimal point           <------>
sprintf("%20.8e", 1234.56789) #=> "      1.23456789e+03"

# precision for `f' is number of
# digits after the decimal point               <------>
sprintf("%20.8f", 1234.56789) #=> "       1234.56789000"

# precision for `g' is number of
# significant digits                          <------->
sprintf("%20.8g", 1234.56789) #=> "           1234.5679"

#                                         <------->
sprintf("%20.8g", 123456789)  #=> "       1.2345679e+08"

# precision for `s' is
# maximum number of characters                    <------>
sprintf("%20.8s", "string test") #=> "            string t"

Examples:

sprintf("%d %04x", 123, 123)               #=> "123 007b"
sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
sprintf("%u", -123)                        #=> "-123"

For more complex formatting, Ruby supports a reference by name. %<name>s style uses format style, but %name style doesn’t.

Examples:

sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
  #=> 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })
  # => "1f"

Overloads:

  • #format(format_string[, arguments...]) ⇒ String

    Returns:

  • #sprintf(format_string[, arguments...]) ⇒ String

    Returns:



4326
4327
4328
4329
4330
# File 'object.c', line 4326

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.

Overloads:

  • #gets(sep = $/[, getline_args]) ⇒ String?

    Returns:

  • #gets(limit[, getline_args]) ⇒ String?

    Returns:

  • #gets(sep, limit[, getline_args]) ⇒ String?

    Returns:



9053
9054
9055
9056
9057
9058
9059
9060
# File 'io.c', line 9053

static VALUE
rb_f_gets(int argc, VALUE *argv, VALUE recv)
{
    if (recv == argf) {
	return argf_gets(argc, argv, argf);
    }
    return rb_funcallv(argf, idGets, argc, argv);
}

#global_variablesArray

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]

Returns:



2029
2030
2031
2032
2033
# File 'eval.c', line 2029

static VALUE
f_global_variables(VALUE _)
{
    return rb_f_global_variables();
}

#Hash(arg) ⇒ Hash

Converts arg to a Hash by calling arg.to_hash. Returns an empty Hash when arg is nil or [].

Hash([])          #=> {}
Hash(nil)         #=> {}
Hash(key: :value) #=> {:key => :value}
Hash([1, 2, 3])   #=> TypeError

Returns:



3992
3993
3994
3995
3996
# File 'object.c', line 3992

static VALUE
rb_f_hash(VALUE obj, VALUE arg)
{
    return rb_Hash(arg);
}

#Integer(arg, base = 0, exception: true) ⇒ Integer?

Converts arg to an Integer. Numeric types are converted directly (with floating point numbers being truncated). base (0, or between 2 and 36) is a base for integer string representation. If arg is a String, when base is omitted or equals zero, radix indicators (0, 0b, and 0x) are honored. In any case, strings should consist only of one or more digits, except for that a sign, one underscore between two digits, and leading/trailing spaces are optional. This behavior is different from that of String#to_i. Non string values will be converted by first trying to_int, then to_i.

Passing nil raises a TypeError, while passing a String that does not conform with numeric representation raises an ArgumentError. This behavior can be altered by passing exception: false, in this case a not convertible value will return nil.

Integer(123.999)    #=> 123
Integer("0x1a")     #=> 26
Integer(Time.new)   #=> 1204973019
Integer("0930", 10) #=> 930
Integer("111", 2)   #=> 7
Integer(" +1_0 ")   #=> 10
Integer(nil)        #=> TypeError: can't convert nil into Integer
Integer("x")        #=> ArgumentError: invalid value for Integer(): "x"

Integer("x", exception: false)        #=> nil

Returns:



3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
# File 'object.c', line 3418

static VALUE
rb_f_integer(int argc, VALUE *argv, VALUE obj)
{
    VALUE arg = Qnil, opts = Qnil;
    int base = 0;

    if (argc > 1) {
        int narg = 1;
        VALUE vbase = rb_check_to_int(argv[1]);
        if (!NIL_P(vbase)) {
            base = NUM2INT(vbase);
            narg = 2;
        }
        if (argc > narg) {
            VALUE hash = rb_check_hash_type(argv[argc-1]);
            if (!NIL_P(hash)) {
                opts = rb_extract_keywords(&hash);
                if (!hash) --argc;
            }
        }
    }
    rb_check_arity(argc, 1, 2);
    arg = argv[0];

    return rb_convert_to_integer(arg, base, opts_exception_p(opts));
}

#iterator?Boolean

Deprecated. Use block_given? instead.

Returns:

  • (Boolean)


2401
2402
2403
2404
2405
2406
# File 'vm_eval.c', line 2401

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.

Yields:

  • (...)

Returns:



886
887
888
889
890
891
# File 'proc.c', line 886

static VALUE
f_lambda(VALUE _)
{
    f_lambda_warn();
    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. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

Returns:

  • (true)


709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'load.c', line 709

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, RTEST(wrap));

    RUBY_DTRACE_HOOK(LOAD_RETURN, RSTRING_PTR(orig_fname));

    return Qtrue;
}

#local_variablesArray

Returns the names of the current local variables.

fred = 1
for i in 1..10
   # ...
end
local_variables   #=> [:fred, :i]

Returns:



2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
# File 'vm_eval.c', line 2324

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 < cfp->iseq->body->local_table_size; i++) {
		local_var_list_add(&vars, cfp->iseq->body->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);
}

#loop { ... } ⇒ Object #loopObject

Repeatedly executes the block.

If no block is given, an enumerator is returned instead.

loop do
  print "Input: "
  line = gets
  break if !line or line =~ /^qQ/
  # ...
end

StopIteration raised in the block breaks the loop. In this case, loop returns the “result” value stored in the exception.

enum = Enumerator.new { |y|
  y << "one"
  y << "two"
  :ok
}

result = loop {
  puts enum.next
} #=> :ok

Overloads:

  • #loop { ... } ⇒ Object

    Yields:



1317
1318
1319
1320
1321
1322
# File 'vm_eval.c', line 1317

static VALUE
rb_f_loop(VALUE self)
{
    RETURN_SIZED_ENUMERATOR(self, 0, 0, rb_f_loop_size);
    return rb_rescue2(loop_i, (VALUE)0, loop_stop, (VALUE)0, rb_eStopIteration, (VALUE)0);
}

#open(path[, mode [, perm]][, opt]) ⇒ IO? #open(path[, mode [, perm]][, opt]) {|io| ... } ⇒ Object

Creates an IO object connected to the given stream, file, or subprocess.

If path does not start with a pipe character (|), treat it as the name of a file to open using the specified mode (defaulting to “r”).

The mode is either a string or an integer. If it is an integer, it must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If it is a string, it is either “fmode”, “fmode:ext_enc”, or “fmode:ext_enc:int_enc”.

See the documentation of IO.new for full documentation of the mode string directives.

If a file is being created, its initial permissions may be set using the perm parameter. See File.new and the open(2) and chmod(2) man pages for a description of permissions.

If a block is specified, it will be invoked with the IO object as a parameter, and the IO will be automatically closed when the block terminates. The call returns the value of the block.

If path starts with a pipe character ("|"), a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess.

If the command following the pipe is a single minus sign ("|-"), Ruby forks, and this subprocess is connected to the parent. If the command is not "-", the subprocess runs the command.

When the subprocess is Ruby (opened via "|-"), the open call returns nil. If a block is associated with the open call, that block will run twice — once in the parent and once in the child.

The block parameter will be an IO object in the parent and nil in the child. The parent’s IO object will be connected to the child’s $stdin and $stdout. The subprocess will be terminated at the end of the block.

Examples

Reading from “testfile”:

open("testfile") do |f|
  print f.gets
end

Produces:

This is line one

Open a subprocess and read its output:

cmd = open("|date")
print cmd.gets
cmd.close

Produces:

Wed Apr  9 08:56:31 CDT 2003

Open a subprocess running the same Ruby program:

f = open("|-", "w+")
if f.nil?
  puts "in Child"
  exit
else
  puts "Got: #{f.gets}"
end

Produces:

Got: in Child

Open a subprocess using a block to receive the IO object:

open "|-" do |f|
  if f then
    # parent process
    puts "Got: #{f.gets}"
  else
    # child process
    puts "in Child"
  end
end

Produces:

Got: in Child

Overloads:

  • #open(path[, mode [, perm]][, opt]) ⇒ IO?

    Returns:

    • (IO, nil)
  • #open(path[, mode [, perm]][, opt]) {|io| ... } ⇒ Object

    Yields:

    • (io)

    Returns:



7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
# File 'io.c', line 7319

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)) {
		    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(obj) ⇒ Object #p(obj1, obj2, ...) ⇒ Array #pnil

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

S = Struct.new(:name, :state)
s = S['dave', 'TX']
p s

produces:

#<S name="dave", state="TX">

Overloads:

  • #p(obj) ⇒ Object

    Returns:

  • #p(obj1, obj2, ...) ⇒ Array

    Returns:

  • #pnil

    Returns:

    • (nil)


7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
# File 'io.c', line 7993

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);
}

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.

print "cat", [1,2,3], 99, "\n"
$, = ", "
$\ = "\n"
print "cat", [1,2,3], 99

produces:

cat12399
cat, 1, 2, 3, 99

Returns:

  • (nil)


7758
7759
7760
7761
7762
7763
# File 'io.c', line 7758

static VALUE
rb_f_print(int argc, const VALUE *argv, VALUE _)
{
    rb_io_print(argc, argv, rb_ractor_stdout());
    return Qnil;
}

#printf(io, string[, obj ... ]) ⇒ nil #printf(string[, obj ... ]) ⇒ nil

Equivalent to:

io.write(sprintf(string, obj, ...))

or

$stdout.write(sprintf(string, obj, ...))

Overloads:

  • #printf(io, string[, obj ... ]) ⇒ nil

    Returns:

    • (nil)
  • #printf(string[, obj ... ]) ⇒ nil

    Returns:

    • (nil)


7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
# File 'io.c', line 7654

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.

Yields:

  • (...)

Returns:



838
839
840
841
842
# File 'proc.c', line 838

static VALUE
f_proc(VALUE _)
{
    return proc_new(rb_cProc, FALSE, TRUE);
}

#putc(int) ⇒ Integer

Equivalent to:

$stdout.putc(int)

Refer to the documentation for IO#putc for important information regarding multi-byte characters.

Returns:



7809
7810
7811
7812
7813
7814
7815
7816
7817
# File 'io.c', line 7809

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 rb_funcallv(r_stdout, rb_intern("putc"), 1, &ch);
}

#puts(obj, ...) ⇒ nil

Equivalent to

$stdout.puts(obj, ...)

Returns:

  • (nil)


7924
7925
7926
7927
7928
7929
7930
7931
7932
# File 'io.c', line 7924

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 rb_funcallv(r_stdout, rb_intern("puts"), argc, argv);
}

#raiseObject #raise(string, cause: $!) ⇒ Object #raise(exception[, string [, array]], cause: $!) ⇒ Object #failObject #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


821
822
823
824
825
# File 'eval.c', line 821

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.

Returns:



1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
# File 'random.c', line 1551

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.

Overloads:

  • #Rational(x, y, exception: true) ⇒ nil

    Returns:

    • (nil)
  • #Rational(arg, exception: true) ⇒ nil

    Returns:

    • (nil)


548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'rational.c', line 548

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 = $/) ⇒ String #readline(limit) ⇒ String #readline(sep, limit) ⇒ String

Equivalent to Kernel::gets, except readline raises EOFError at end of file.

Overloads:



9129
9130
9131
9132
9133
9134
9135
9136
# File 'io.c', line 9129

static VALUE
rb_f_readline(int argc, VALUE *argv, VALUE recv)
{
    if (recv == argf) {
	return argf_readline(argc, argv, argf);
    }
    return rb_funcallv(argf, rb_intern("readline"), argc, argv);
}

#readlines(sep = $/) ⇒ Array #readlines(limit) ⇒ Array #readlines(sep, limit) ⇒ Array

Returns an array containing the lines returned by calling Kernel.gets(sep) until the end of file.

Overloads:



9183
9184
9185
9186
9187
9188
9189
9190
# File 'io.c', line 9183

static VALUE
rb_f_readlines(int argc, VALUE *argv, VALUE recv)
{
    if (recv == argf) {
	return argf_readlines(argc, argv, argf);
    }
    return rb_funcallv(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 “.dll”, 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 any shared library extension. For example, on Linux the socket extension is “socket.so” and require 'socket.dll' 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.

Returns:

  • (Boolean)


835
836
837
838
839
# File 'load.c', line 835

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 requiring file’s path. If the file’s path cannot be determined a LoadError is raised. If a file is loaded true is returned and false otherwise.

Returns:

  • (Boolean)


849
850
851
852
853
854
855
856
857
858
# File 'load.c', line 849

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(rb_file_absolute_path(fname, base));
}

#select(read_array[, write_array [, error_array [, timeout]]]) ⇒ Array?

Calls select(2) system call. It monitors given arrays of IO objects, waits until one or more of IO objects are ready for reading, are ready for writing, and have pending exceptions respectively, and returns an array that contains arrays of those IO objects. It will return nil if optional timeout value is given and no IO object is ready in timeout seconds.

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 nonblocking 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 nonblocking 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 nonblocking 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) manual on GNU/Linux system.

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

Parameters

read_array

an array of IO objects that wait until ready for read

write_array

an array of IO objects that wait until ready for write

error_array

an array of IO objects that wait for exceptions

timeout

a numeric value in second

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
}

produces:

ping pong
ping pong
ping pong
(snipped)
ping

Returns:



9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
# File 'io.c', line 9736

static VALUE
rb_f_select(int argc, VALUE *argv, VALUE obj)
{
    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 * a filename * a line number * an object id * a binding * 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

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, classname|
 printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
   }
   t = Test.new
   t.test

line prog.rb:11               false
   c-call prog.rb:11        new    Class
   c-call prog.rb:11 initialize   Object
 c-return prog.rb:11 initialize   Object
 c-return prog.rb:11        new    Class
line prog.rb:12               false

call prog.rb:2 test Test

line prog.rb:3        test     Test
line prog.rb:4        test     Test
   return prog.rb:4        test     Test

Overloads:

  • #set_trace_func(proc) ⇒ Proc

    Returns:

  • #set_trace_func(nil) ⇒ nil

    Returns:

    • (nil)


524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'vm_trace.c', line 524

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([duration]) ⇒ Integer

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. Called without an argument, sleep() will sleep forever.

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

Returns:



5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
# File 'process.c', line 5103

static VALUE
rb_f_sleep(int argc, VALUE *argv, VALUE _)
{
    time_t beg = time(0);
    VALUE scheduler = rb_scheduler_current();

    if (scheduler != Qnil) {
        rb_scheduler_kernel_sleepv(scheduler, argc, argv);
    }
    else {
        if (argc == 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,][,options]) ⇒ Object

spawn executes specified command and return its pid.

pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2")
Process.wait pid

pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'")
Process.wait pid

This method is similar to Kernel#system but it doesn’t wait for the command to finish.

The parent process should use Process.wait to collect the termination status of its child or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

spawn has bunch of options to specify process attributes:

env: hash
  name => val : set the environment variable
  name => nil : unset the environment variable

  the keys and the values except for +nil+ must be strings.
command...:
  commandline                 : command line string which is passed to the standard shell
  cmdname, arg1, ...          : command name and one or more arguments (This form does not use the shell. See below for caveats.)
  [cmdname, argv0], arg1, ... : command name, argv[0] and zero or more arguments (no shell)
options: hash
  clearing environment variables:
    :unsetenv_others => true   : clear environment variables except specified by env
    :unsetenv_others => false  : don't clear (default)
  process group:
    :pgroup => true or 0 : make a new process group
    :pgroup => pgid      : join the specified process group
    :pgroup => nil       : don't change the process group (default)
  create new process group: Windows only
    :new_pgroup => true  : the new process is the root process of a new process group
    :new_pgroup => false : don't create a new process group (default)
  resource limit: resourcename is core, cpu, data, etc.  See Process.setrlimit.
    :rlimit_resourcename => limit
    :rlimit_resourcename => [cur_limit, max_limit]
  umask:
    :umask => int
  redirection:
    key:
      FD              : single file descriptor in child process
      [FD, FD, ...]   : multiple file descriptor in child process
    value:
      FD                        : redirect to the file descriptor in parent process
      string                    : redirect to file with open(string, "r" or "w")
      [string]                  : redirect to file with open(string, File::RDONLY)
      [string, open_mode]       : redirect to file with open(string, open_mode, 0644)
      [string, open_mode, perm] : redirect to file with open(string, open_mode, perm)
      [:child, FD]              : redirect to the redirected file descriptor
      :close                    : close the file descriptor in child process
    FD is one of follows
      :in     : the file descriptor 0 which is the standard input
      :out    : the file descriptor 1 which is the standard output
      :err    : the file descriptor 2 which is the standard error
      integer : the file descriptor of specified the integer
      io      : the file descriptor specified as io.fileno
  file descriptor inheritance: close non-redirected non-standard fds (3, 4, 5, ...) or not
    :close_others => false  : inherit
  current directory:
    :chdir => str

The cmdname, arg1, ... form does not use the shell. However, on different OSes, different things are provided as built-in commands. An example of this is ‘echo’, which is a built-in on Windows, but is a normal program on Linux and Mac OS X. This means that Process.spawn 'echo', '%Path%' will display the contents of the %Path% environment variable on Windows, but Process.spawn 'echo', '$PATH' prints the literal $PATH.

If a hash is given as env, the environment is updated by env before exec(2) in the child process. If a pair in env has nil as the value, the variable is deleted.

# set FOO as BAR and unset BAZ.
pid = spawn({"FOO"=>"BAR", "BAZ"=>nil}, command)

If a hash is given as options, it specifies process group, create new process group, resource limit, current directory, umask and redirects for the child process. Also, it can be specified to clear environment variables.

The :unsetenv_others key in options specifies to clear environment variables, other than specified by env.

pid = spawn(command, :unsetenv_others=>true) # no environment variable
pid = spawn({"FOO"=>"BAR"}, command, :unsetenv_others=>true) # FOO only

The :pgroup key in options specifies a process group. The corresponding value should be true, zero, a positive integer, or nil. true and zero cause the process to be a process leader of a new process group. A non-zero positive integer causes the process to join the provided process group. The default value, nil, causes the process to remain in the same process group.

pid = spawn(command, :pgroup=>true) # process leader
pid = spawn(command, :pgroup=>10) # belongs to the process group 10

The :new_pgroup key in options specifies to pass CREATE_NEW_PROCESS_GROUP flag to CreateProcessW() that is Windows API. This option is only for Windows. true means the new process is the root process of the new process group. The new process has CTRL+C disabled. This flag is necessary for Process.kill(:SIGINT, pid) on the subprocess. :new_pgroup is false by default.

pid = spawn(command, :new_pgroup=>true)  # new process group
pid = spawn(command, :new_pgroup=>false) # same process group

The :rlimit_foo key specifies a resource limit. foo should be one of resource types such as core. The corresponding value should be an integer or an array which have one or two integers: same as cur_limit and max_limit arguments for Process.setrlimit.

cur, max = Process.getrlimit(:CORE)
pid = spawn(command, :rlimit_core=>[0,max]) # disable core temporary.
pid = spawn(command, :rlimit_core=>max) # enable core dump
pid = spawn(command, :rlimit_core=>0) # never dump core.

The :umask key in options specifies the umask.

pid = spawn(command, :umask=>077)

The :in, :out, :err, an integer, an IO and an array key specifies a redirection. The redirection maps a file descriptor in the child process.

For example, stderr can be merged into stdout as follows:

pid = spawn(command, :err=>:out)
pid = spawn(command, 2=>1)
pid = spawn(command, STDERR=>:out)
pid = spawn(command, STDERR=>STDOUT)

The hash keys specifies a file descriptor in the child process started by #spawn. :err, 2 and STDERR specifies the standard error stream (stderr).

The hash values specifies a file descriptor in the parent process which invokes #spawn. :out, 1 and STDOUT specifies the standard output stream (stdout).

In the above example, the standard output in the child process is not specified. So it is inherited from the parent process.

The standard input stream (stdin) can be specified by :in, 0 and STDIN.

A filename can be specified as a hash value.

pid = spawn(command, :in=>"/dev/null") # read mode
pid = spawn(command, :out=>"/dev/null") # write mode
pid = spawn(command, :err=>"log") # write mode
pid = spawn(command, [:out, :err]=>"/dev/null") # write mode
pid = spawn(command, 3=>"/dev/null") # read mode

For stdout and stderr (and combination of them), it is opened in write mode. Otherwise read mode is used.

For specifying flags and permission of file creation explicitly, an array is used instead.

pid = spawn(command, :in=>["file"]) # read mode is assumed
pid = spawn(command, :in=>["file", "r"])
pid = spawn(command, :out=>["log", "w"]) # 0644 assumed
pid = spawn(command, :out=>["log", "w", 0600])
pid = spawn(command, :out=>["log", File::WRONLY|File::EXCL|File::CREAT, 0600])

The array specifies a filename, flags and permission. The flags can be a string or an integer. If the flags is omitted or nil, File::RDONLY is assumed. The permission should be an integer. If the permission is omitted or nil, 0644 is assumed.

If an array of IOs and integers are specified as a hash key, all the elements are redirected.

# stdout and stderr is redirected to log file.
# The file "log" is opened just once.
pid = spawn(command, [:out, :err]=>["log", "w"])

Another way to merge multiple file descriptors is [:child, fd]. [:child, fd] means the file descriptor in the child process. This is different from fd. For example, :err=>:out means redirecting child stderr to parent stdout. But :err=>[:child, :out] means redirecting child stderr to child stdout. They differ if stdout is redirected in the child process as follows.

# stdout and stderr is redirected to log file.
# The file "log" is opened just once.
pid = spawn(command, :out=>["log", "w"], :err=>[:child, :out])

[:child, :out] can be used to merge stderr into stdout in IO.popen. In this case, IO.popen redirects stdout to a pipe in the child process and [:child, :out] refers the redirected stdout.

io = IO.popen(["sh", "-c", "echo out; echo err >&2", :err=>[:child, :out]])
p io.read #=> "out\nerr\n"

The :chdir key in options specifies the current directory.

pid = spawn(command, :chdir=>"/var/tmp")

spawn closes all non-standard unspecified descriptors by default. The “standard” descriptors are 0, 1 and 2. This behavior is specified by :close_others option. :close_others doesn’t affect the standard descriptors which are closed only if :close is specified explicitly.

pid = spawn(command, :close_others=>true)  # close 3,4,5,... (default)
pid = spawn(command, :close_others=>false) # don't close 3,4,5,...

:close_others is false by default for spawn and IO.popen.

Note that fds which close-on-exec flag is already set are closed regardless of :close_others option.

So IO.pipe and spawn can be used as IO.popen.

# similar to r = IO.popen(command)
r, w = IO.pipe
pid = spawn(command, :out=>w)   # r, w is closed in the child process.
w.close

:close is specified as a hash value to close a fd individually.

f = open(foo)
system(command, f=>:close)        # don't inherit f.

If a file descriptor need to be inherited, io=>io can be used.

# valgrind has --log-fd option for log destination.
# log_w=>log_w indicates log_w.fileno inherits to child process.
log_r, log_w = IO.pipe
pid = spawn("valgrind", "--log-fd=#{log_w.fileno}", "echo", "a", log_w=>log_w)
log_w.close
p log_r.read

It is also possible to exchange file descriptors.

pid = spawn(command, :out=>:err, :err=>:out)

The hash keys specify file descriptors in the child process. The hash values specifies file descriptors in the parent process. So the above specifies exchanging stdout and stderr. Internally, spawn uses an extra file descriptor to resolve such cyclic file descriptor mapping.

See Kernel.exec for the standard shell.



5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
# File 'process.c', line 5059

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
}

#format(format_string[, arguments...]) ⇒ String #sprintf(format_string[, arguments...]) ⇒ String

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.

The syntax of a format sequence is as follows.

%[flags][width][.precision]type

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:

Field |  Integer Format
------+--------------------------------------------------------------
  b   | Convert argument as a binary number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..1'.
  B   | Equivalent to `b', but uses an uppercase 0B for prefix
      | in the alternative format by #.
  d   | Convert argument as a decimal number.
  i   | Identical to `d'.
  o   | Convert argument as an octal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..7'.
  u   | Identical to `d'.
  x   | Convert argument as a hexadecimal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..f' (representing an infinite string of
      | leading 'ff's).
  X   | Equivalent to `x', but uses uppercase letters.

Field |  Float Format
------+--------------------------------------------------------------
  e   | Convert floating point argument into exponential notation
      | with one digit before the decimal point as [-]d.dddddde[+-]dd.
      | The precision specifies the number of digits after the decimal
      | point (defaulting to six).
  E   | Equivalent to `e', but uses an uppercase E to indicate
      | the exponent.
  f   | Convert floating point argument as [-]ddd.dddddd,
      | where the precision specifies the number of digits after
      | the decimal point.
  g   | Convert a floating point number using exponential form
      | if the exponent is less than -4 or greater than or
      | equal to the precision, or in dd.dddd form otherwise.
      | The precision specifies the number of significant digits.
  G   | Equivalent to `g', but use an uppercase `E' in exponent form.
  a   | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
      | which is consisted from optional sign, "0x", fraction part
      | as hexadecimal, "p", and exponential part as decimal.
  A   | Equivalent to `a', but use uppercase `X' and `P'.

Field |  Other Format
------+--------------------------------------------------------------
  c   | Argument is the numeric code for a single character or
      | a single character string itself.
  p   | The valuing of argument.inspect.
  s   | Argument is a string to be substituted.  If the format
      | sequence contains a precision, at most that many characters
      | will be copied.
  %   | A percent sign itself will be displayed.  No argument taken.

The flags modifies the behavior of the formats. The flag characters are:

Flag     | Applies to    | Meaning
---------+---------------+-----------------------------------------
space    | bBdiouxX      | Leave a space at the start of
         | aAeEfgG       | non-negative numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
(digit)$ | all           | Specifies the absolute argument number
         |               | for this field.  Absolute and relative
         |               | argument numbers cannot be mixed in a
         |               | sprintf string.
---------+---------------+-----------------------------------------
 #       | bBoxX         | Use an alternative format.
         | aAeEfgG       | For the conversions `o', increase the precision
         |               | until the first digit will be `0' if
         |               | it is not formatted as complements.
         |               | For the conversions `x', `X', `b' and `B'
         |               | on non-zero, prefix the result with ``0x'',
         |               | ``0X'', ``0b'' and ``0B'', respectively.
         |               | For `a', `A', `e', `E', `f', `g', and 'G',
         |               | force a decimal point to be added,
         |               | even if no digits follow.
         |               | For `g' and 'G', do not remove trailing zeros.
---------+---------------+-----------------------------------------
+        | bBdiouxX      | Add a leading plus sign to non-negative
         | aAeEfgG       | numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
-        | all           | Left-justify the result of this conversion.
---------+---------------+-----------------------------------------
0 (zero) | bBdiouxX      | Pad with zeros, not spaces.
         | aAeEfgG       | For `o', `x', `X', `b' and `B', radix-1
         | (numeric fmt) | is used for negative numbers formatted as
         |               | complements.
---------+---------------+-----------------------------------------
*        | all           | Use the next argument as the field width.
         |               | If negative, left-justify the result. If the
         |               | asterisk is followed by a number and a dollar
         |               | sign, use the indicated argument as the width.

Examples of flags:

# `+' and space flag specifies the sign of non-negative numbers.
sprintf("%d", 123)  #=> "123"
sprintf("%+d", 123) #=> "+123"
sprintf("% d", 123) #=> " 123"

# `#' flag for `o' increases number of digits to show `0'.
# `+' and space flag changes format of negative numbers.
sprintf("%o", 123)   #=> "173"
sprintf("%#o", 123)  #=> "0173"
sprintf("%+o", -123) #=> "-173"
sprintf("%o", -123)  #=> "..7605"
sprintf("%#o", -123) #=> "..7605"

# `#' flag for `x' add a prefix `0x' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%x", 123)   #=> "7b"
sprintf("%#x", 123)  #=> "0x7b"
sprintf("%+x", -123) #=> "-7b"
sprintf("%x", -123)  #=> "..f85"
sprintf("%#x", -123) #=> "0x..f85"
sprintf("%#x", 0)    #=> "0"

# `#' for `X' uses the prefix `0X'.
sprintf("%X", 123)  #=> "7B"
sprintf("%#X", 123) #=> "0X7B"

# `#' flag for `b' add a prefix `0b' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%b", 123)   #=> "1111011"
sprintf("%#b", 123)  #=> "0b1111011"
sprintf("%+b", -123) #=> "-1111011"
sprintf("%b", -123)  #=> "..10000101"
sprintf("%#b", -123) #=> "0b..10000101"
sprintf("%#b", 0)    #=> "0"

# `#' for `B' uses the prefix `0B'.
sprintf("%B", 123)  #=> "1111011"
sprintf("%#B", 123) #=> "0B1111011"

# `#' for `e' forces to show the decimal point.
sprintf("%.0e", 1)  #=> "1e+00"
sprintf("%#.0e", 1) #=> "1.e+00"

# `#' for `f' forces to show the decimal point.
sprintf("%.0f", 1234)  #=> "1234"
sprintf("%#.0f", 1234) #=> "1234."

# `#' for `g' forces to show the decimal point.
# It also disables stripping lowest zeros.
sprintf("%g", 123.4)   #=> "123.4"
sprintf("%#g", 123.4)  #=> "123.400"
sprintf("%g", 123456)  #=> "123456"
sprintf("%#g", 123456) #=> "123456."

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Examples of width:

# padding is done by spaces,       width=20
# 0 or radix-1.             <------------------>
sprintf("%20d", 123)   #=> "                 123"
sprintf("%+20d", 123)  #=> "                +123"
sprintf("%020d", 123)  #=> "00000000000000000123"
sprintf("%+020d", 123) #=> "+0000000000000000123"
sprintf("% 020d", 123) #=> " 0000000000000000123"
sprintf("%-20d", 123)  #=> "123                 "
sprintf("%-+20d", 123) #=> "+123                "
sprintf("%- 20d", 123) #=> " 123                "
sprintf("%020x", -123) #=> "..ffffffffffffffff85"

For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

Examples of precisions:

# precision for `d', 'o', 'x' and 'b' is
# minimum number of digits               <------>
sprintf("%20.8d", 123)  #=> "            00000123"
sprintf("%20.8o", 123)  #=> "            00000173"
sprintf("%20.8x", 123)  #=> "            0000007b"
sprintf("%20.8b", 123)  #=> "            01111011"
sprintf("%20.8d", -123) #=> "           -00000123"
sprintf("%20.8o", -123) #=> "            ..777605"
sprintf("%20.8x", -123) #=> "            ..ffff85"
sprintf("%20.8b", -11)  #=> "            ..110101"

# "0x" and "0b" for `#x' and `#b' is not counted for
# precision but "0" for `#o' is counted.  <------>
sprintf("%#20.8d", 123)  #=> "            00000123"
sprintf("%#20.8o", 123)  #=> "            00000173"
sprintf("%#20.8x", 123)  #=> "          0x0000007b"
sprintf("%#20.8b", 123)  #=> "          0b01111011"
sprintf("%#20.8d", -123) #=> "           -00000123"
sprintf("%#20.8o", -123) #=> "            ..777605"
sprintf("%#20.8x", -123) #=> "          0x..ffff85"
sprintf("%#20.8b", -11)  #=> "          0b..110101"

# precision for `e' is number of
# digits after the decimal point           <------>
sprintf("%20.8e", 1234.56789) #=> "      1.23456789e+03"

# precision for `f' is number of
# digits after the decimal point               <------>
sprintf("%20.8f", 1234.56789) #=> "       1234.56789000"

# precision for `g' is number of
# significant digits                          <------->
sprintf("%20.8g", 1234.56789) #=> "           1234.5679"

#                                         <------->
sprintf("%20.8g", 123456789)  #=> "       1.2345679e+08"

# precision for `s' is
# maximum number of characters                    <------>
sprintf("%20.8s", "string test") #=> "            string t"

Examples:

sprintf("%d %04x", 123, 123)               #=> "123 007b"
sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
sprintf("%u", -123)                        #=> "-123"

For more complex formatting, Ruby supports a reference by name. %<name>s style uses format style, but %name style doesn’t.

Examples:

sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
  #=> 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })
  # => "1f"

Overloads:

  • #format(format_string[, arguments...]) ⇒ String

    Returns:

  • #sprintf(format_string[, arguments...]) ⇒ String

    Returns:



4326
4327
4328
4329
4330
# File 'object.c', line 4326

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]


855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'random.c', line 855

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(arg) ⇒ String

Returns arg as a String.

First tries to call its to_str method, then its to_s method.

String(self)        #=> "main"
String(self.class)  #=> "Object"
String(123456)      #=> "123456"

Returns:



3911
3912
3913
3914
3915
# File 'object.c', line 3911

static VALUE
rb_f_string(VALUE obj, VALUE arg)
{
    return rb_String(arg);
}

#syscall(num[, args...]) ⇒ Integer

Calls the operating system function identified by num and returns the result of the function or raises SystemCallError if it failed.

Arguments for the function can follow num. They must be either String objects or Integer objects. A String object is passed as a pointer to the byte sequence. An Integer object is passed as an integer whose bit size is same as a pointer. Up to nine parameters may be passed.

The function identified by num is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h.

syscall 4, 1, "hello\n", 6   # '4' is write(2) on our box

produces:

hello

Calling syscall on a platform which does not have any way to an arbitrary system function just fails with NotImplementedError.

Note: syscall is essentially unsafe and unportable. Feel free to shoot your foot. The DL (Fiddle) library is preferred for safer and a bit more portable programming.

Returns:



10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
# File 'io.c', line 10205

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, ...

Executes command… in a subshell. command… is one of following forms.

commandline

command line string which is passed to the standard shell

cmdname, arg1, ...

command name and one or more arguments (no shell)

[cmdname, argv0], arg1, ...

command name, argv[0] and zero or more arguments (no shell)

system returns true if the command gives zero exit status, false for non zero exit status. Returns nil if command execution fails. An error status is available in $?.

If the exception: true argument is passed, the method raises an exception instead of returning false or nil.

The arguments are processed in the same way as for Kernel#spawn.

The hash arguments, env and options, are same as #exec and #spawn. See Kernel#spawn for details.

system("echo *")
system("echo", "*")

produces:

config.h main.rb
*

Error handling:

system("cat nonexistent.txt")
# => false
system("catt nonexistent.txt")
# => nil

system("cat nonexistent.txt", exception: true)
# RuntimeError (Command failed with exit 1: cat)
system("catt nonexistent.txt", exception: true)
# Errno::ENOENT (No such file or directory - catt)

See Kernel#exec for the standard shell.

Returns:

  • (true, false, nil)


4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
# File 'process.c', line 4732

static VALUE
rb_f_system(int argc, VALUE *argv, VALUE _)
{
    /*
     * n.b. using alloca for now to simplify future Thread::Light code
     * when we need to use malloc for non-native Fiber
     */
    struct waitpid_state *w = alloca(sizeof(struct waitpid_state));
    rb_pid_t pid; /* may be different from waitpid_state.pid on exec failure */
    VALUE execarg_obj;
    struct rb_execarg *eargp;
    int exec_errnum;

    execarg_obj = rb_execarg_new(argc, argv, TRUE, TRUE);
    eargp = rb_execarg_get(execarg_obj);
    w->ec = GET_EC();
    waitpid_state_init(w, 0, 0);
    eargp->waitpid_state = w;
    pid = rb_execarg_spawn(execarg_obj, 0, 0);
    exec_errnum = pid < 0 ? errno : 0;

#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
    if (w->pid > 0) {
        /* `pid' (not w->pid) may be < 0 here if execve failed in child */
        if (WAITPID_USE_SIGCHLD) {
            rb_ensure(waitpid_sleep, (VALUE)w, waitpid_cleanup, (VALUE)w);
        }
        else {
            waitpid_no_SIGCHLD(w);
        }
        rb_last_status_set(w->status, w->ret);
    }
#endif
    if (w->pid < 0 /* fork failure */ || pid < 0 /* exec failure */) {
        if (eargp->exception) {
            int err = exec_errnum ? exec_errnum : w->errnum;
            VALUE command = eargp->invoke.sh.shell_script;
            RB_GC_GUARD(execarg_obj);
            rb_syserr_fail_str(err, command);
        }
        else {
            return Qnil;
        }
    }
    if (w->status == EXIT_SUCCESS) return Qtrue;
    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, w->status), ": ");
        rb_str_append(str, command);
        RB_GC_GUARD(execarg_obj);
        rb_exc_raise(rb_exc_new_str(rb_eRuntimeError, str));
    }
    else {
        return Qfalse;
    }
}

#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 \CF{setgid} bit
     |         | set (false under NT)
"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

Returns:



5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
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
# File 'file.c', line 5296

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.



2119
2120
2121
2122
2123
2124
2125
2126
2127
# File 'vm_eval.c', line 2119

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'

Overloads:

  • #trace_var(symbol, cmd) ⇒ nil

    Returns:

    • (nil)
  • #trace_var(symbol) {|val| ... } ⇒ nil

    Yields:

    • (val)

    Returns:

    • (nil)


2058
2059
2060
2061
2062
# File 'eval.c', line 2058

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

Overloads:



1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
# File 'signal.c', line 1387

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.

Returns:



2074
2075
2076
2077
2078
# File 'eval.c', line 2074

static VALUE
f_untrace_var(int c, const VALUE *a, VALUE _)
{
    return rb_f_untrace_var(c, a);
}