module Kernel

TheKernel module is included by classObject, so its methods are available in every Ruby object.

TheKernel instance methods are documented in classObject while the module methods are documented here. These methods are called without a receiver and thus can be called in functional form:

sprintf"%.1f",1.234#=> "1.2"

What’s Here

Module Kernel provides methods that are useful for:

Converting

Querying

Exiting

Exceptions

IO

Procs

Tracing

Subprocesses

Loading

Yielding

Random Values

Other

Public Class Methods

Source
# File pathname_builtin.rb, line 1171defPathname(path)# :doc:returnpathifPathname===pathPathname.new(path)end

Creates aPathname object.

Source
# File lib/uri/common.rb, line 911defURI(uri)ifuri.is_a?(URI::Generic)urielsifuri =String.try_convert(uri)URI.parse(uri)elseraiseArgumentError,"bad argument (expected URI object or URI string)"endend

Returns a URI object derived from the givenuri, which may be a URI string or an existing URI object:

require'uri'# Returns a new URI.uri =URI('http://github.com/ruby/ruby')# => #<URI::HTTP http://github.com/ruby/ruby># Returns the given URI.URI(uri)# => #<URI::HTTP http://github.com/ruby/ruby>

You must require ‘uri’ to use this method.

Source
# File lib/pp.rb, line 731defpp(*objs)objs.each {|obj|PP.pp(obj)  }objs.size<=1?objs.first:objsend

prints arguments in pretty form.

pp returns argument(s).

Public Instance Methods

Source
static VALUErb_f_callee_name(VALUE _){    ID fname = prev_frame_callee(); /* need *callee* ID */    if (fname) {        return ID2SYM(fname);    }    else {        return Qnil;    }}

Returns the called name of the current method as aSymbol. If called outside of a method, it returnsnil.

Source
static VALUEf_current_dirname(VALUE _){    VALUE base = rb_current_realfilepath();    if (NIL_P(base)) {        return Qnil;    }    base = rb_file_dirname(base);    return base;}

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__ isnil, it returnsnil. The return value equals toFile.dirname(File.realpath(__FILE__)).

Source
static VALUErb_f_method_name(VALUE _){    ID fname = prev_frame_func(); /* need *method* ID */    if (fname) {        return ID2SYM(fname);    }    else {        return Qnil;    }}

Returns the name at the definition of the current method as aSymbol. If called outside of a method, it returnsnil.

Source
static VALUErb_f_backquote(VALUE obj, VALUE str){    VALUE port;    VALUE result;    rb_io_t *fptr;    StringValue(str);    rb_last_status_clear();    port = pipe_open_s(str, "r", FMODE_READABLE|DEFAULT_TEXTMODE, NULL);    if (NIL_P(port)) return rb_str_new(0,0);    GetOpenFile(port, fptr);    result = read_all(fptr, remain_size(fptr), Qnil);    rb_io_close(port);    rb_io_fptr_cleanup_all(fptr);    RB_GC_GUARD(port);    return result;}

Returns the$stdout output from runningcommand in a subshell; sets global variable$? to the process status.

This method has potential security vulnerabilities if called with untrusted input; seeCommand Injection.

Examples:

$ `date`                 # => "Wed Apr  9 08:56:30 CDT 2003\n"$ `echo oops && exit 99` # => "oops\n"$ $?                     # => #<Process::Status: pid 17088 exit 99>$ $?.exitstatus          # => 99

The built-in syntax%x{...} uses this method.

Source
static VALUErb_f_array(VALUE obj, VALUE arg){    return rb_Array(arg);}

Returns an array converted fromobject.

Tries to convertobject to an array usingto_ary first andto_a second:

Array([0,1,2])# => [0, 1, 2]Array({foo:0,bar:1})# => [[:foo, 0], [:bar, 1]]Array(0..4)# => [0, 1, 2, 3, 4]

Returnsobject in an array,[object], ifobject cannot be converted:

Array(:foo)# => [:foo]
Source
static VALUEnucomp_f_complex(int argc, VALUE *argv, VALUE klass){    VALUE a1, a2, opts = Qnil;    int raise = TRUE;    if (rb_scan_args(argc, argv, "11:", &a1, &a2, &opts) == 1) {        a2 = Qundef;    }    if (!NIL_P(opts)) {        raise = rb_opts_exception_p(opts, raise);    }    if (argc > 0 && CLASS_OF(a1) == rb_cComplex && UNDEF_P(a2)) {        return a1;    }    return nucomp_convert(rb_cComplex, a1, a2, raise);}

Returns a new Complex object if the arguments are valid; otherwise raises an exception ifexception istrue; otherwise returnsnil.

WithNumeric argumentsreal andimag, returnsComplex.rect(real, imag) if the arguments are valid.

With string arguments, returns a new Complex object if the argument is valid; the string may have:

  • One or two numeric substrings, each of which specifies aComplex,Float,Integer,Numeric, orRational value, specifyingrectangular coordinates:

    • Sign-separated real and imaginary numeric substrings (with trailing character'i'):

      Complex('1+2i')# => (1+2i)Complex('+1+2i')# => (1+2i)Complex('+1-2i')# => (1-2i)Complex('-1+2i')# => (-1+2i)Complex('-1-2i')# => (-1-2i)
    • Real-only numeric string (without trailing character'i'):

      Complex('1')# => (1+0i)Complex('+1')# => (1+0i)Complex('-1')# => (-1+0i)
    • Imaginary-only numeric string (with trailing character'i'):

      Complex('1i')# => (0+1i)Complex('+1i')# => (0+1i)Complex('-1i')# => (0-1i)
  • At-sign separated real and imaginary rational substrings, each of which specifies aRational value, specifyingpolar coordinates:

    Complex('1/2@3/4')# => (0.36584443443691045+0.34081938001166706i)Complex('+1/2@+3/4')# => (0.36584443443691045+0.34081938001166706i)Complex('+1/2@-3/4')# => (0.36584443443691045-0.34081938001166706i)Complex('-1/2@+3/4')# => (-0.36584443443691045-0.34081938001166706i)Complex('-1/2@-3/4')# => (-0.36584443443691045+0.34081938001166706i)
Source
# File kernel.rb, line 194defFloat(arg,exception:true)ifPrimitive.mandatory_only?Primitive.rb_f_float1(arg)elsePrimitive.rb_f_float(arg,exception)endend

Returnsarg converted to a float.Numeric types are converted directly, and with exception toString andnil, the rest are converted usingarg.to_f. Converting aString with invalid characters will result in anArgumentError. Convertingnil generates aTypeError. Exceptions can be suppressed by passingexception: false.

Float(1)#=> 1.0Float("123.456")#=> 123.456Float("123.0_badstring")#=> ArgumentError: invalid value for Float(): "123.0_badstring"Float(nil)#=> TypeError: can't convert nil into FloatFloat("123.0_badstring",exception:false)#=> nil
Source
static VALUErb_f_hash(VALUE obj, VALUE arg){    return rb_Hash(arg);}

Returns a hash converted fromobject.

  • Ifobject is:

    • A hash, returnsobject.

    • An empty array ornil, returns an empty hash.

  • Otherwise, ifobject.to_hash returns a hash, returns that hash.

  • Otherwise, returnsTypeError.

Examples:

Hash({foo:0,bar:1})# => {:foo=>0, :bar=>1}Hash(nil)# => {}Hash([])# => {}
Source
# File kernel.rb, line 287defInteger(arg,base =0,exception:true)ifPrimitive.mandatory_only?Primitive.rb_f_integer1(arg)elsePrimitive.rb_f_integer(arg,base,exception)endend

Returns an integer converted fromobject.

Tries to convertobject to an integer usingto_int first andto_i second; see below for exceptions.

With a non-zerobase,object must be a string or convertible to a string.

Numeric objects

With an integer argumentobject given, returnsobject:

Integer(1)# => 1Integer(-1)# => -1

With a floating-point argumentobject given, returnsobject truncated to an integer:

Integer(1.9)# => 1  # Rounds toward zero.Integer(-1.9)# => -1 # Rounds toward zero.

String objects

With a string argumentobject and zerobase given, returnsobject converted to an integer in base 10:

Integer('100')# => 100Integer('-100')# => -100

Withbase zero, stringobject may contain leading characters to specify the actual base (radix indicator):

Integer('0100')# => 64  # Leading '0' specifies base 8.Integer('0b100')# => 4   # Leading '0b' specifies base 2.Integer('0x100')# => 256 # Leading '0x' specifies base 16.

With a positivebase (in range 2..36) given, returnsobject converted to an integer in the given base:

Integer('100',2)# => 4Integer('100',8)# => 64Integer('-100',16)# => -256

With a negativebase (in range -36..-2) given, returnsobject converted to the radix indicator if it exists orbase:

Integer('0x100',-2)# => 256Integer('100',-2)# => 4Integer('0b100',-8)# => 4Integer('100',-8)# => 64Integer('0o100',-10)# => 64Integer('100',-10)# => 100

base -1 is equivalent to the -10 case.

When converting strings, surrounding whitespace and embedded underscores are allowed and ignored:

Integer(' 100 ')# => 100Integer('-1_0_0',16)# => -256

Other classes

Examples withobject of various other classes:

Integer(Rational(9,10))# => 0  # Rounds toward zero.Integer(Complex(2,0))# => 2  # Imaginary part must be zero.Integer(Time.now)# => 1650974042

Keywords

With the optional keyword argumentexception given astrue (the default):

Withexception given asfalse, an exception of any kind is suppressed andnil is returned.

Source
static VALUEnurat_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);}

Returnsx/y orarg as aRational.

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")#=> ArgumentErrorRational(nil)#=> TypeErrorRational(1,nil)#=> TypeErrorRational("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 alsoString#to_r.

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

Returns a string converted fromobject.

Tries to convertobject to a string usingto_str first andto_s second:

String([0,1,2])# => "[0, 1, 2]"String(0..5)# => "0..5"String({foo:0,bar:1})# => "{foo: 0, bar: 1}"

RaisesTypeError ifobject cannot be converted to a string.

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

Terminates execution immediately, effectively by callingKernel.exit(false).

If string argumentmsg is given, it is written to STDERR prior to termination; otherwise, if an exception was raised, prints its message and backtrace.

Source
static VALUErb_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;}

Convertsblock to aProc 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.

defdo_at_exit(str1)at_exit {printstr1 }endat_exit {puts"cruel world" }do_at_exit("goodbye ")exit

produces:

goodbyecruelworld
Source
static VALUErb_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);}

Registersfilename to be loaded (using Kernel::require) the first time thatconst (which may be aString or a symbol) is accessed.

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

Ifconst is defined as autoload, the file name to be loaded is replaced withfilename. Ifconst is defined but not as autoload, does nothing.

Files that are currently being loaded must not be registered for autoload.

Source
static VALUErb_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);}

Returnsfilename to be loaded ifname is registered asautoload in the current namespace or one of its ancestors.

autoload(:B,"b")autoload?(:B)#=> "b"moduleCautoload(:D,"d")autoload?(:D)#=> "d"autoload?(:B)#=> nilendclassEautoload(:F,"f")autoload?(:F)#=> "f"autoload?(:B)#=> "b"end
Source
static VALUErb_f_binding(VALUE self){    return rb_binding_new();}

Returns aBinding object, describing the variable and method bindings at the point of call. This object can be used when callingBinding#eval to execute the evaluated command in this environment, or extracting its local variables.

classUserdefinitialize(name,position)@name =name@position =positionenddefget_bindingbindingendenduser =User.new('Joan','manager')template ='{name: @name, position: @position}'# evaluate template in context of the objecteval(template,user.get_binding)#=> {:name=>"Joan", :position=>"manager"}

Binding#local_variable_get can be used to access the variables whose names are reserved Ruby keywords:

# This is valid parameter declaration, but `if` parameter can't# be accessed by name, because it is a reserved word.defvalidate(field,validation,if:nil)condition =binding.local_variable_get('if')returnunlesscondition# ...Some implementation ...endvalidate(:name,:empty?,if:false)# skips validationvalidate(:name,:empty?,if:true)# performs validation
Source
static VALUErb_f_block_given_p(VALUE _){    rb_execution_context_t *ec = GET_EC();    rb_control_frame_t *cfp = ec->cfp;    cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp));    return RBOOL(cfp != NULL && VM_CF_BLOCK_HANDLER(cfp) != VM_BLOCK_HANDLER_NONE);}

Returnstrue ifyield would execute a block in the current context. Theiterator? form is mildly deprecated.

deftryifblock_given?yieldelse"no block"endendtry#=> "no block"try {"hello" }#=> "hello"trydo"hello"end#=> "hello"
Source
static VALUErb_callcc(VALUE self){    volatile int called;    volatile VALUE val = cont_capture(&called);    if (called) {        return val;    }    else {        return rb_yield(val);    }}

Generates aContinuation object, which it passes to the associated block. You need torequire 'continuation' before using this method. Performing acont.call will cause thecallcc to return (as will falling through the end of the block). The value returned by thecallcc is the value of the block, or the value passed tocont.call. See classContinuation for more details. Also seeKernel#throw for an alternative mechanism for unwinding a call stack.

Source
static VALUErb_f_caller(int argc, VALUE *argv, VALUE _){    return ec_backtrace_to_ary(GET_EC(), argc, argv, 1, 1, 1);}

Returns the current execution stack—an array containing strings in the formfile:line orfile:line: in `method'.

The optionalstart parameter determines the number of initial stack entries to omit from the top of the stack.

A second optionallength parameter can be used to limit how many entries are returned from the stack.

Returnsnil ifstart 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.

defa(skip)caller(skip)enddefb(skip)a(skip)enddefc(skip)b(skip)endc(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
Source
static VALUErb_f_caller_locations(int argc, VALUE *argv, VALUE _){    return ec_backtrace_to_ary(GET_EC(), argc, argv, 1, 1, 0);}

Returns the current execution stack—an array containing backtrace location objects.

SeeThread::Backtrace::Location for more information.

The optionalstart parameter determines the number of initial stack entries to omit from the top of the stack.

A second optionallength parameter can be used to limit how many entries are returned from the stack.

Returnsnil ifstart 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.

Source
static VALUErb_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);}

catch executes its block. Ifthrow is not called, the block executes normally, andcatch returns the value of the last expression evaluated.

catch(1) {123 }# => 123

Ifthrow(tag2, val) is called, Ruby searches up its stack for acatch block whosetag has the sameobject_id astag2. When found, the block stops executing and returnsval (ornil if no second argument was given tothrow).

catch(1) {throw(1,456) }# => 456catch(1) {throw(1) }# => nil

Whentag is passed as the first argument,catch yields it as the parameter of the block.

catch(1) {|x|x+2 }# => 3

When notag is given,catch yields a new unique object (as fromObject.new) as the block parameter. This object can then be used as the argument tothrow, and will match the correctcatch block.

catchdo|obj_A|catchdo|obj_B|throw(obj_B,123)puts"This puts is not reached"endputs"This puts is displayed"456end# => 456catchdo|obj_A|catchdo|obj_B|throw(obj_A,123)puts"This puts is still not reached"endputs"Now this puts is also not reached"456end# => 123
Source
static VALUErb_f_chomp(int argc, VALUE *argv, VALUE _){    VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chomp"), argc, argv);    rb_lastline_set(str);    return str;}

Equivalent to$_ = $_.chomp(string). SeeString#chomp. Available only when -p/-n command line option specified.

Source
static VALUErb_f_chop(VALUE _){    VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chop"), 0, 0);    rb_lastline_set(str);    return str;}

Equivalent to($_.dup).chop!, exceptnil is never returned. SeeString#chop!. Available only when -p/-n command line option specified.

Source
# File kernel.rb, line 18defclassPrimitive.attr!:leafPrimitive.cexpr!'rb_obj_class_must(self)'end

Returns the class ofobj. This method must always be called with an explicit receiver, asclass is also a reserved word in Ruby.

1.class#=> Integerself.class#=> Object
Source
# File kernel.rb, line 47defclone(freeze:nil)Primitive.rb_obj_clone2(freeze)end

Produces a shallow copy ofobj—the instance variables ofobj are copied, but not the objects they reference.clone copies the frozen value state ofobj, unless the:freeze keyword argument is given with a false or true value. See also the discussion underObject#dup.

classKlassattr_accessor:strends1 =Klass.new#=> #<Klass:0x401b3a38>s1.str ="Hello"#=> "Hello"s2 =s1.clone#=> #<Klass:0x401b3998 @str="Hello">s2.str[1,4] ="i"#=> "i"s1.inspect#=> "#<Klass:0x401b3a38 @str=\"Hi\">"s2.inspect#=> "#<Klass:0x401b3998 @str=\"Hi\">"

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Source
VALUErb_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);    StringValue(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);}

Evaluates the Ruby expression(s) instring. Ifbinding is given, which must be aBinding object, the evaluation is performed in its context. If the optionalfilename andlineno parameters are present, they will be used when reporting syntax errors.

defget_binding(str)returnbindingendstr ="hello"eval"str + ' Fred'"#=> "hello Fred"eval"str + ' Fred'",get_binding("bye")#=> "bye Fred"
Source
static VALUEf_exec(int c, const VALUE *a, VALUE _){    rb_f_exec(c, a);    UNREACHABLE_RETURN(Qnil);}

Replaces the current process by doing one of the following:

  • Passing stringcommand_line to the shell.

  • Invoking the executable atexe_path.

This method has potential security vulnerabilities if called with untrusted input; seeCommand Injection.

The new process is created using theexec system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).

Argumentenv, if given, is a hash that affectsENV for the new process; seeExecution Environment.

Argumentoptions is a hash of options for the new process; seeExecution Options.

The first required argument is one of the following:

  • command_line if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.

  • exe_path otherwise.

Argumentcommand_line

String argumentcommand_line is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:

exec('if true; then echo "Foo"; fi')# Shell reserved word.exec('exit')# Built-in.exec('date > date.tmp')# Contains meta character.

The command line may also contain arguments and options for the command:

exec('echo "Foo"')

Output:

Foo

SeeExecution Shell for details about the shell.

Raises an exception if the new process could not execute.

Argumentexe_path

Argumentexe_path is one of the following:

  • The string path to an executable to be called.

  • A 2-element array containing the path to an executable and the string to be used as the name of the executing process.

Example:

exec('/usr/bin/date')

Output:

Sat Aug 26 09:38:00 AM CDT 2023

Ruby invokes the executable directly. This form does not use the shell; seeArguments args for caveats.

exec('doesnt_exist')# Raises Errno::ENOENT

If one or moreargs is given, each is an argument or option to be passed to the executable:

exec('echo','C*')exec('echo','hello','world')

Output:

C*hello world

Raises an exception if the new process could not execute.

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

Initiates termination of the Ruby script by raisingSystemExit; the exception may be caught. Returns exit statusstatus to the underlying operating system.

Valuestrue andfalse for argumentstatus indicate, respectively, success and failure; The meanings of integer values are system-dependent.

Example:

beginexitputs'Never get here.'rescueSystemExitputs'Rescued a SystemExit exception.'endputs'After begin block.'

Output:

Rescued a SystemExit exception.After begin block.

Just prior to final termination, Ruby executes any at-exit procedures (see Kernel::at_exit) and any object finalizers (seeObjectSpace::define_finalizer).

Example:

at_exit {puts'In at_exit function.' }ObjectSpace.define_finalizer('string',proc {puts'In finalizer.' })exit

Output:

In at_exit function.In finalizer.
Source
static VALUErb_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);}

Exits the process immediately; no exit handlers are called. Returns exit statusstatus to the underlying operating system.

Process.exit!(true)

Valuestrue andfalse for argumentstatus indicate, respectively, success and failure; The meanings of integer values are system-dependent.

Alias for:raise
Source
static VALUErb_f_fork(VALUE obj){    rb_pid_t pid;    pid = rb_call_proc__fork();    if (pid == 0) {        if (rb_block_given_p()) {            int status;            rb_protect(rb_yield, Qundef, &status);            ruby_stop(status);        }        return Qnil;    }    return PIDT2NUM(pid);}

Creates a child process.

With a block given, runs the block in the child process; on block exit, the child terminates with a status of zero:

puts"Before the fork: #{Process.pid}"forkdoputs"In the child process: #{Process.pid}"end# => 382141puts"After the fork: #{Process.pid}"

Output:

Beforethefork:420496Afterthefork:420496Inthechildprocess:420520

With no block given, thefork call returns twice:

  • Once in the parent process, returning the pid of the child process.

  • Once in the child process, returningnil.

Example:

puts"This is the first line before the fork (pid #{Process.pid})"putsforkputs"This is the second line after the fork (pid #{Process.pid})"

Output:

Thisisthefirstlinebeforethefork (pid420199)420223Thisisthesecondlineafterthefork (pid420199)Thisisthesecondlineafterthefork (pid420223)

In either case, the child process may exit usingKernel.exit! to avoid the call toKernel#at_exit.

To avoid zombie processes, the parent process should call either:

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

Note that methodfork is available on some platforms, but not on others:

Process.respond_to?(:fork)# => true # Would be false on some.

If not, you may use ::spawn instead offork.

Alias for:sprintf
Source
# File kernel.rb, line 67deffrozen?Primitive.attr!:leafPrimitive.cexpr!'rb_obj_frozen_p(self)'end

Returns the freeze status ofobj.

a = ["a","b","c" ]a.freeze#=> ["a", "b", "c"]a.frozen?#=> true
Source
static VALUErb_f_gets(int argc, VALUE *argv, VALUE recv){    if (recv == argf) {        return argf_gets(argc, argv, argf);    }    return forward(argf, idGets, argc, argv);}

Returns (and assigns to$_) the next line from the list of files inARGV (or$*), or from standard input if no files are present on the command line. Returnsnil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator ofnil 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 inARGV,gets(nil) will read the contents one file at a time.

ARGV<<"testfile"printwhilegets

produces:

ThisislineoneThisislinetwoThisislinethreeAndsoon...

The style of programming using$_ as an implicit parameter is gradually losing favor in the Ruby community.

Source
static VALUEf_global_variables(VALUE _){    return rb_f_global_variables();}

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]
Source
static VALUErb_f_gsub(int argc, VALUE *argv, VALUE _){    VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("gsub"), argc, argv);    rb_lastline_set(str);    return str;}

Equivalent to$_.gsub..., except that$_ will be updated if substitution occurs. Available only when -p/-n command line option specified.

Source
static VALUErb_f_iterator_p(VALUE self){    rb_warn_deprecated("iterator?", "block_given?");    return rb_f_block_given_p(self);}

Deprecated. Use block_given? instead.

Source
static VALUEf_lambda(VALUE _){    f_lambda_filter_non_literal();    return rb_block_lambda();}

Equivalent toProc.new, except the resultingProc objects check the number of parameters passed when called.

Source
static VALUErb_f_load(int argc, VALUE *argv, VALUE _){    VALUE fname, wrap;    rb_scan_args(argc, argv, "11", &fname, &wrap);    return load_entrypoint_internal(fname, wrap);}

Loads and executes the Ruby program in the filefilename.

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, aLoadError will be raised.

If the optionalwrap parameter istrue, the loaded script will be executed under an anonymous module. If the optionalwrap parameter is a module, the loaded script will be executed under the given module. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

Source
static VALUErb_f_local_variables(VALUE _){    struct local_var_list vars;    rb_execution_context_t *ec = GET_EC();    rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp));    unsigned int i;    local_var_list_init(&vars);    while (cfp) {        if (cfp->iseq) {            for (i = 0; i < ISEQ_BODY(cfp->iseq)->local_table_size; i++) {                local_var_list_add(&vars, ISEQ_BODY(cfp->iseq)->local_table[i]);            }        }        if (!VM_ENV_LOCAL_P(cfp->ep)) {            /* block */            const VALUE *ep = VM_CF_PREV_EP(cfp);            if (vm_collect_local_variables_in_heap(ep, &vars)) {                break;            }            else {                while (cfp->ep != ep) {                    cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);                }            }        }        else {            break;        }    }    return local_var_list_finish(&vars);}

Returns the names of the current local variables.

fred =1foriin1..10# ...endlocal_variables#=> [:fred, :i]
Source
# File kernel.rb, line 161defloopPrimitive.attr!:inline_blockunlessdefined?(yield)returnPrimitive.cexpr!'SIZED_ENUMERATOR(self, 0, 0, rb_f_loop_size)'endbeginwhiletrueyieldendrescueStopIteration=>ee.resultendend

Repeatedly executes the block.

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

loopdoprint"Input: "line =gets# break if q, Q is entered or EOF signal (Ctrl-D on Unix, Ctrl-Z on windows) is sentbreakif!lineorline=~/^q/i# ...end

AStopIteration 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 {putsenum.next}#=> :ok
Source
static VALUErb_f_open(int argc, VALUE *argv, VALUE _){    ID to_open = 0;    int redirect = FALSE;    if (argc >= 1) {        CONST_ID(to_open, "to_open");        if (rb_respond_to(argv[0], to_open)) {            redirect = TRUE;        }        else {            VALUE tmp = argv[0];            FilePathValue(tmp);            if (NIL_P(tmp)) {                redirect = TRUE;            }            else {                VALUE cmd = check_pipe_command(tmp);                if (!NIL_P(cmd)) {                    // TODO: when removed in 4.0, update command_injection.rdoc                    rb_warn_deprecated_to_remove_at(4.0, "Calling Kernel#open with a leading '|'", "IO.popen");                    argv[0] = cmd;                    return rb_io_s_popen(argc, argv, rb_cIO);                }            }        }    }    if (redirect) {        VALUE io = rb_funcallv_kw(argv[0], to_open, argc-1, argv+1, RB_PASS_CALLED_KEYWORDS);        if (rb_block_given_p()) {            return rb_ensure(rb_yield, io, io_close, io);        }        return io;    }    return rb_io_s_open(argc, argv, rb_cFile);}

Creates anIO object connected to the given file.

This method has potential security vulnerabilities if called with untrusted input; seeCommand Injection.

With no block given, file stream is returned:

open('t.txt')# => #<File:t.txt>

With a block given, calls the block with the open file stream, then closes the stream:

open('t.txt') {|f|pf }# => #<File:t.txt (closed)>

Output:

#<File:t.txt>

SeeFile.open for details.

Source
static VALUErb_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);}

For each objectobj, executes:

$stdout.write(obj.inspect,"\n")

With one object given, returns the object; with multiple objects given, returns an array containing the objects; with no object given, returnsnil.

Examples:

r =Range.new(0,4)pr# => 0..4p [r,r,r]# => [0..4, 0..4, 0..4]p# => nil

Output:

0..4[0..4,0..4,0..4]

Kernel#p is designed for debugging purposes. Ruby implementations may defineKernel#p to be uninterruptible in whole or in part. On CRuby,Kernel#p‘s writing of data is uninterruptible.

Source
# File lib/pp.rb, line 724defpretty_inspectPP.pp(self,''.dup)end

Returns a pretty printed object as a string.

See thePP module for more information.

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

Equivalent to$stdout.print(*objects), this method is the straightforward way to write to$stdout.

Writes the given objects to$stdout; returnsnil. Appends the output record separator$OUTPUT_RECORD_SEPARATOR$\), if it is notnil.

With argumentobjects given, for each object:

  • Converts via its methodto_s if not a string.

  • Writes tostdout.

  • If not the last object, writes the output field separator$OUTPUT_FIELD_SEPARATOR ($, if it is notnil.

With default separators:

objects = [0,0.0,Rational(0,1),Complex(0,0),:zero,'zero']$OUTPUT_RECORD_SEPARATOR$OUTPUT_FIELD_SEPARATORprint(*objects)

Output:

nilnil00.00/10+0izerozero

With specified separators:

$OUTPUT_RECORD_SEPARATOR ="\n"$OUTPUT_FIELD_SEPARATOR =','print(*objects)

Output:

0,0.0,0/1,0+0i,zero,zero

With no argument given, writes the content of$_ (which is usually the most recent user input):

gets# Sets $_ to the most recent user input.print# Prints $_.
Source
static VALUErb_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;}

Equivalent to:

io.write(sprintf(format_string,*objects))

For details onformat_string, seeFormat Specifications.

With the single argumentformat_string, formatsobjects into the string, then writes the formatted string to $stdout:

printf('%4.4d %10s %2.2f',24,24,24.0)

Output (on $stdout):

0024         24 24.00#

With argumentsio andformat_string, formatsobjects into the string, then writes the formatted string toio:

printf($stderr,'%4.4d %10s %2.2f',24,24,24.0)

Output (on $stderr):

0024         24 24.00# => nil

With no arguments, does nothing.

Source
static VALUEf_proc(VALUE _){    return proc_new(rb_cProc, FALSE);}

Equivalent toProc.new.

Source
static VALUErb_f_putc(VALUE recv, VALUE ch){    VALUE r_stdout = rb_ractor_stdout();    if (recv == r_stdout) {        return rb_io_putc(recv, ch);    }    return forward(r_stdout, rb_intern("putc"), 1, &ch);}

Equivalent to:

$stdout.putc(int)

SeeIO#putc for important information regarding multi-byte characters.

Source
static VALUErb_f_puts(int argc, VALUE *argv, VALUE recv){    VALUE r_stdout = rb_ractor_stdout();    if (recv == r_stdout) {        return rb_io_puts(argc, argv, recv);    }    return forward(r_stdout, rb_intern("puts"), argc, argv);}

Equivalent to

$stdout.puts(objects)
Source
static VALUEf_raise(int c, VALUE *v, VALUE _){    return rb_f_raise(c, v);}

Raises an exception; seeExceptions.

Argumentexception sets the class of the new exception; it should be classException or one of its subclasses (most commonly,RuntimeError orStandardError), or an instance of one of those classes:

beginraise(StandardError)rescue=>xpx.classend# => StandardError

Argumentmessage sets the stored message in the new exception, which may be retrieved by methodException#message; the message must be astring-convertible object ornil:

beginraise(StandardError,'Boom')rescue=>xpx.messageend# => "Boom"

If argumentmessage is not given, the message is the exception class name.

SeeMessages.

Argumentbacktrace might be used to modify the backtrace of the new exception, as reported byException#backtrace andException#backtrace_locations; the backtrace must be an array ofThread::Backtrace::Location, an array of strings, a single string, ornil.

Using the array ofThread::Backtrace::Location instances is the most consistent option and should be preferred when possible. The necessary value might be obtained fromcaller_locations, or copied fromException#backtrace_locations of another error:

begindo_some_work()rescueZeroDivisionError=>exraise(LogicalError,"You have an error in your math",ex.backtrace_locations)end

The ways, bothException#backtrace andException#backtrace_locations of the raised error are set to the same backtrace.

When the desired stack of locations is not available and should be constructed from scratch, an array of strings or a singular string can be used. In this case, onlyException#backtrace is set:

beginraise(StandardError,'Boom',%w[dsl.rb:3 framework.rb:1])rescue=>expex.backtrace# => ["dsl.rb:3", "framework.rb:1"]pex.backtrace_locations# => nilend

If argumentbacktrace is not given, the backtrace is set according to an array ofThread::Backtrace::Location objects, as derived from the call stack.

SeeBacktraces.

Keyword argumentcause sets the stored cause in the new exception, which may be retrieved by methodException#cause; the cause must be an exception object (Exception or one of its subclasses), ornil:

beginraise(StandardError,cause:RuntimeError.new)rescue=>xpx.causeend# => #<RuntimeError: RuntimeError>

If keyword argumentcause is not given, the cause is the value of$!.

SeeCause.

In the alternate calling sequence, where argumentexceptionnot given, raises a new exception of the class given by$!, or of classRuntimeError if$! isnil:

beginraiserescue=>xpxend# => RuntimeError

With argumentexception not given, argumentmessage and keyword argumentcause may be given, but argumentbacktrace may not be given.

Also aliased as:fail
Source
static VALUErb_f_rand(int argc, VALUE *argv, VALUE obj){    VALUE vmax;    rb_random_t *rnd = default_rand_start();    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));}

If called without an argument, or ifmax.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

Whenmax.abs is greater than or equal to 1,rand returns a pseudo-random integer greater than or equal to 0 and less thanmax.to_i.abs.

rand(100)#=> 12

Whenmax is aRange,rand returns a random number whererange.member?(number) == true.

Negative or floating point values formax are allowed, but may give surprising results.

rand(-100)# => 87rand(-0.5)# => 0.8130921818028143rand(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.

Related:Random.rand.

rand(100.0)# => 64 (Integer because max.to_i is 100)Random.rand(100.0)# => 30.315320967824523
Source
static VALUErb_f_readline(int argc, VALUE *argv, VALUE recv){    if (recv == argf) {        return argf_readline(argc, argv, argf);    }    return forward(argf, rb_intern("readline"), argc, argv);}

Equivalent to methodKernel#gets, except that it raises an exception if called at end-of-stream:

$ cat t.txt | ruby -e "p readlines; readline"["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]in `readline': end of file reached (EOFError)

Optional keyword argumentchomp specifies whether line separators are to be omitted.

Source
static VALUErb_f_readlines(int argc, VALUE *argv, VALUE recv){    if (recv == argf) {        return argf_readlines(argc, argv, argf);    }    return forward(argf, rb_intern("readlines"), argc, argv);}

Returns an array containing the lines returned by callingKernel#gets until the end-of-stream is reached; (seeLine IO).

With only string argumentsep given, returns the remaining lines as determined by line separatorsep, ornil if none; seeLine Separator:

# Default separator.$ cat t.txt | ruby -e "p readlines"["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]# Specified separator.$ cat t.txt | ruby -e "p readlines 'li'"["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]# Get-all separator.$ cat t.txt | ruby -e "p readlines nil"["First line\nSecond line\n\nFourth line\nFifth line\n"]# Get-paragraph separator.$ cat t.txt | ruby -e "p readlines ''"["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]

With only integer argumentlimit given, limits the number of bytes in the line; seeLine Limit:

$cat t.txt | ruby -e "p readlines 10"["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"]$cat t.txt | ruby -e "p readlines 11"["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"]$cat t.txt | ruby -e "p readlines 12"["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]

With argumentssep andlimit given, combines the two behaviors (seeLine Separator and Line Limit).

Optional keyword argumentchomp specifies whether line separators are to be omitted:

$ cat t.txt | ruby -e "p readlines(chomp: true)"["First line", "Second line", "", "Fourth line", "Fifth line"]

Optional keyword argumentsenc_opts specify encoding options; seeEncoding options.

Source
VALUErb_f_require_relative(VALUE obj, VALUE fname){    return rb_require_relative_entrypoint(fname);}

Ruby tries to load the library namedstring relative to the directory containing the requiring file. If the file does not exist aLoadError is raised. Returnstrue if the file was loaded andfalse if the file was already loaded before.

Source
static VALUErb_f_select(int argc, VALUE *argv, VALUE obj){    VALUE scheduler = rb_fiber_scheduler_current();    if (scheduler != Qnil) {        // It's optionally supported.        VALUE result = rb_fiber_scheduler_io_selectv(scheduler, argc, argv);        if (!UNDEF_P(result)) return result;    }    VALUE timeout;    struct select_args args;    struct timeval timerec;    int i;    rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);    if (NIL_P(timeout) || is_pos_inf(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);}

Invokes system callselect(2), which monitors multiple file descriptors, waiting until one or more of the file descriptors becomes ready for some class of I/O operation.

Not implemented on all platforms.

Each of the argumentsread_ios,write_ios, anderror_ios is an array ofIO objects.

Argumenttimeout is a numeric value (such as integer or float) timeout interval in seconds.timeout can also benil orFloat::INFINITY.nil andFloat::INFINITY means no timeout.

The method monitors the IO objects given in all three arrays, waiting for some to be ready; returns a 3-element array whose elements are:

  • An array of the objects inread_ios that are ready for reading.

  • An array of the objects inwrite_ios that are ready for writing.

  • An array of the objects inerror_ios have pending exceptions.

If no object becomes ready within the giventimeout,nil is returned.

IO.select peeks the buffer of IO objects for testing readability. If the IO buffer is not empty, IO.select immediately notifies readability. This “peek” only happens for IO objects. It does not happen for IO-like objects such asOpenSSL::SSL::SSLSocket.

The best way to use IO.select is invoking it after non-blocking methods such as read_nonblock, write_nonblock, etc. The methods raise an exception which is extended byIO::WaitReadable orIO::WaitWritable. The modules notify how the caller should wait with IO.select. IfIO::WaitReadable is raised, the caller should wait for reading. IfIO::WaitWritable is raised, the caller should wait for writing.

So, blocking read (readpartial) can be emulated using read_nonblock and IO.select as follows:

beginresult =io_like.read_nonblock(maxlen)rescueIO::WaitReadableIO.select([io_like])retryrescueIO::WaitWritableIO.select(nil, [io_like])retryend

Especially, the combination of non-blocking methods and IO.select is preferred forIO like objects such asOpenSSL::SSL::SSLSocket. It has to_io method to return underlyingIO 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 fromOpenSSL::SSL::SSLSocket object.

The most likely situation is thatOpenSSL::SSL::SSLSocket buffers some data. IO.select doesn’t see the buffer. So IO.select can block whenOpenSSL::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 butOpenSSL::SSL::SSLSocket cannot decrypt a byte andOpenSSL::SSL::SSLSocket#readpartial will block.

Also, the remote side can request SSL renegotiation which forces the local SSL engine to write some data. This meansOpenSSL::SSL::SSLSocket#readpartial may invoke write system call and it can block. In such a situation,OpenSSL::SSL::SSLSocket#read_nonblock raisesIO::WaitWritable instead of blocking. So, the caller should wait for ready for writability as above example.

The combination of non-blocking methods and IO.select is also useful for streams such as tty, pipe socket socket when multiple processes read from a stream.

Finally, Linux kernel developers don’t guarantee that readability of select(2) means readability of following read(2) even for a single process; seeselect(2)

Invoking IO.select beforeIO#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 andIO.select as follows:IO::WaitReadable should also be rescued for SSL renegotiation inOpenSSL::SSL::SSLSocket.

while0<string.bytesizebeginwritten =io_like.write_nonblock(string)rescueIO::WaitReadableIO.select([io_like])retryrescueIO::WaitWritableIO.select(nil, [io_like])retryendstring =string.byteslice(written..-1)end

Example:

rp,wp =IO.pipemesg ="ping "100.times {# IO.select follows IO#read.  Not the best way to use IO.select.rs,ws, =IO.select([rp], [wp])ifr =rs[0]ret =r.read(5)printretcaseretwhen/ping/mesg ="pong\n"when/pong/mesg ="ping "endendifw =ws[0]w.write(mesg)end}

Output:

pingpongpingpongpingpong(snipped)ping
Source
static VALUEset_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;}

Establishesproc as the handler for tracing, or disables tracing if the parameter isnil.

Note: this method is obsolete, please useTracePoint instead.

proc takes up to six parameters:

  • an event name string

  • a filename string

  • a line number

  • a method name symbol, or nil

  • a binding, or nil

  • the class, module, or nil

proc is invoked whenever an event occurs.

Events are:

"c-call"

call a C-language routine

"c-return"

return from a C-language routine

"call"

call a Ruby method

"class"

start a class or module definition

"end"

finish a class or module definition

"line"

execute code on a new line

"raise"

raise an exception

"return"

return from a Ruby method

Tracing is disabled within the context ofproc.

classTestdeftesta =1b =2endendset_trace_funcproc {|event,file,line,id,binding,class_or_module|printf"%8s %s:%-2d %16p %14p\n",event,file,line,id,class_or_module}t =Test.newt.test

Produces:

c-return prog.rb:8   :set_trace_func         Kernel    line prog.rb:11              nil            nil  c-call prog.rb:11             :new          Class  c-call prog.rb:11      :initialize    BasicObjectc-return prog.rb:11      :initialize    BasicObjectc-return prog.rb:11             :new          Class    line prog.rb:12              nil            nil    call prog.rb:2             :test           Test    line prog.rb:3             :test           Test    line prog.rb:4             :test           Test  return prog.rb:5             :test           Test
Source
static VALUErb_f_sleep(int argc, VALUE *argv, VALUE _){    time_t beg = time(0);    VALUE scheduler = rb_fiber_scheduler_current();    if (scheduler != Qnil) {        rb_fiber_scheduler_kernel_sleepv(scheduler, argc, argv);    }    else {        if (argc == 0 || (argc == 1 && NIL_P(argv[0]))) {            rb_thread_sleep_forever();        }        else {            rb_check_arity(argc, 0, 1);            rb_thread_wait_for(rb_time_interval(argv[0]));        }    }    time_t end = time(0) - beg;    return TIMET2NUM(end);}

Suspends execution of the current thread for the number of seconds specified by numeric argumentsecs, or forever ifsecs isnil; returns the integer number of seconds suspended (rounded).

Time.new# => 2008-03-08 19:56:19 +0900sleep1.2# => 1Time.new# => 2008-03-08 19:56:20 +0900sleep1.9# => 2Time.new# => 2008-03-08 19:56:22 +0900
Source
static VALUErb_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}

Creates a new child process by doing one of the following in that process:

  • Passing stringcommand_line to the shell.

  • Invoking the executable atexe_path.

This method has potential security vulnerabilities if called with untrusted input; seeCommand Injection.

Returns the process ID (pid) of the new process, without waiting for it to complete.

To avoid zombie processes, the parent process should call either:

The new process is created using theexec system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).

Argumentenv, if given, is a hash that affectsENV for the new process; seeExecution Environment.

Argumentoptions is a hash of options for the new process; seeExecution Options.

The first required argument is one of the following:

  • command_line if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.

  • exe_path otherwise.

Argumentcommand_line

String argumentcommand_line is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:

spawn('if true; then echo "Foo"; fi')# => 798847 # Shell reserved word.Process.wait# => 798847spawn('exit')# => 798848 # Built-in.Process.wait# => 798848spawn('date > /tmp/date.tmp')# => 798879 # Contains meta character.Process.wait# => 798849spawn('date > /nop/date.tmp')# => 798882 # Issues error message.Process.wait# => 798882

The command line may also contain arguments and options for the command:

spawn('echo "Foo"')# => 799031Process.wait# => 799031

Output:

Foo

SeeExecution Shell for details about the shell.

Raises an exception if the new process could not execute.

Argumentexe_path

Argumentexe_path is one of the following:

  • The string path to an executable to be called.

  • A 2-element array containing the path to an executable to be called, and the string to be used as the name of the executing process.

    spawn('/usr/bin/date')# Path to date on Unix-style system.Process.wait

    Output:

    Mon Aug 28 11:43:10 AM CDT 2023

Ruby invokes the executable directly. This form does not use the shell; seeArguments args for caveats.

If one or moreargs is given, each is an argument or option to be passed to the executable:

spawn('echo','C*')# => 799392Process.wait# => 799392spawn('echo','hello','world')# => 799393Process.wait# => 799393

Output:

C*hello world

Raises an exception if the new process could not execute.

Source
static VALUEf_sprintf(int c, const VALUE *v, VALUE _){    return rb_f_sprintf(c, v);}

Returns the string resulting from formattingobjects intoformat_string.

For details onformat_string, seeFormat Specifications.

Also aliased as:format
Source
static VALUErb_f_srand(int argc, VALUE *argv, VALUE obj){    VALUE seed, old;    rb_random_mt_t *r = default_mt();    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;}

Seeds the system pseudo-random number generator, withnumber. The previous seed value is returned.

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

srand1234# => 268519324636777531569100071560086917274[rand,rand ]# => [0.1915194503788923, 0.6221087710398319][rand(10),rand(1000) ]# => [4, 664]srand1234# => 1234[rand,rand ]# => [0.1915194503788923, 0.6221087710398319]
Source
static VALUErb_f_sub(int argc, VALUE *argv, VALUE _){    VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("sub"), argc, argv);    rb_lastline_set(str);    return str;}

Equivalent to$_.sub(args), except that$_ will be updated if substitution occurs. Available only when -p/-n command line option specified.

Source
static VALUErb_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)) {            StringValue(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}

Invokes Posix system callsyscall(2), which calls a specified function.

Calls the operating system function identified byinteger_callno; returns the result of the function or raisesSystemCallError if it failed. The effect of the call is platform-dependent. The arguments and returned value are platform-dependent.

For each ofarguments: if it is an integer, it is passed directly; if it is a string, it is interpreted as a binary sequence of bytes. There may be as many as nine such arguments.

Argumentsinteger_callno andargument, as well as the returned value, are platform-dependent.

Note: Methodsyscall is essentially unsafe and unportable. The DL (Fiddle) library is preferred for safer and a bit more portable programming.

Not implemented on all platforms.

Source
static VALUErb_f_system(int argc, VALUE *argv, VALUE _){    rb_thread_t *th = GET_THREAD();    VALUE execarg_obj = rb_execarg_new(argc, argv, TRUE, TRUE);    struct rb_execarg *eargp = rb_execarg_get(execarg_obj);    struct rb_process_status status = {0};    eargp->status = &status;    last_status_clear(th);    // This function can set the thread's last status.    // May be different from waitpid_state.pid on exec failure.    rb_pid_t pid = rb_execarg_spawn(execarg_obj, 0, 0);    if (pid > 0) {        VALUE status = rb_process_status_wait(pid, 0);        struct rb_process_status *data = rb_check_typeddata(status, &rb_process_status_type);        // Set the last status:        rb_obj_freeze(status);        th->last_status = status;        if (data->status == EXIT_SUCCESS) {            return Qtrue;        }        if (data->error != 0) {            if (eargp->exception) {                VALUE command = eargp->invoke.sh.shell_script;                RB_GC_GUARD(execarg_obj);                rb_syserr_fail_str(data->error, command);            }            else {                return Qnil;            }        }        else if (eargp->exception) {            VALUE command = eargp->invoke.sh.shell_script;            VALUE str = rb_str_new_cstr("Command failed with");            rb_str_cat_cstr(pst_message_status(str, data->status), ": ");            rb_str_append(str, command);            RB_GC_GUARD(execarg_obj);            rb_exc_raise(rb_exc_new_str(rb_eRuntimeError, str));        }        else {            return Qfalse;        }        RB_GC_GUARD(status);    }    if (eargp->exception) {        VALUE command = eargp->invoke.sh.shell_script;        RB_GC_GUARD(execarg_obj);        rb_syserr_fail_str(errno, command);    }    else {        return Qnil;    }}

Creates a new child process by doing one of the following in that process:

  • Passing stringcommand_line to the shell.

  • Invoking the executable atexe_path.

This method has potential security vulnerabilities if called with untrusted input; seeCommand Injection.

Returns:

  • true if the command exits with status zero.

  • false if the exit status is a non-zero integer.

  • nil if the command could not execute.

Raises an exception (instead of returningfalse ornil) if keyword argumentexception is set totrue.

Assigns the command’s error status to$?.

The new process is created using thesystem system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).

Argumentenv, if given, is a hash that affectsENV for the new process; seeExecution Environment.

Argumentoptions is a hash of options for the new process; seeExecution Options.

The first required argument is one of the following:

  • command_line if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.

  • exe_path otherwise.

Argumentcommand_line

String argumentcommand_line is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:

system('if true; then echo "Foo"; fi')# => true  # Shell reserved word.system('exit')# => true  # Built-in.system('date > /tmp/date.tmp')# => true  # Contains meta character.system('date > /nop/date.tmp')# => falsesystem('date > /nop/date.tmp',exception:true)# Raises RuntimeError.

Assigns the command’s error status to$?:

system('exit')# => true  # Built-in.$?# => #<Process::Status: pid 640610 exit 0>system('date > /nop/date.tmp')# => false$?# => #<Process::Status: pid 640742 exit 2>

The command line may also contain arguments and options for the command:

system('echo "Foo"')# => true

Output:

Foo

SeeExecution Shell for details about the shell.

Raises an exception if the new process could not execute.

Argumentexe_path

Argumentexe_path is one of the following:

  • The string path to an executable to be called.

  • A 2-element array containing the path to an executable and the string to be used as the name of the executing process.

Example:

system('/usr/bin/date')# => true # Path to date on Unix-style system.system('foo')# => nil  # Command failed.

Output:

Mon Aug 28 11:43:10 AM CDT 2023

Assigns the command’s error status to$?:

system('/usr/bin/date')# => true$?# => #<Process::Status: pid 645605 exit 0>system('foo')# => nil$?# => #<Process::Status: pid 645608 exit 127>

Ruby invokes the executable directly. This form does not use the shell; seeArguments args for caveats.

system('doesnt_exist')# => nil

If one or moreargs is given, each is an argument or option to be passed to the executable:

system('echo','C*')# => truesystem('echo','hello','world')# => true

Output:

C*hello world

Raises an exception if the new process could not execute.

Source
# File kernel.rb, line 89deftapPrimitive.attr!:inline_blockyield(self)selfend

Yields self to the block and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

(1..10)                  .tap {|x|puts"original: #{x}" }  .to_a                  .tap {|x|puts"array:    #{x}" }  .select {|x|x.even? } .tap {|x|puts"evens:    #{x}" }  .map {|x|x*x }        .tap {|x|puts"squares:  #{x}" }
Source
static VALUErb_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;        stat_timestamp 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);}

Performs a test on one or both of thefilesystem entities at the given pathspath0 andpath1:

  • Each pathpath0 orpath1 points to a file, directory, device, pipe, etc.

  • Characterchar selects a specific test.

The tests:

  • Each of these tests operates only on the entity atpath0, and returnstrue orfalse; for a non-existent entity, returnsfalse (does not raise exception):

    CharacterTest
    'b'Whether the entity is a block device.
    'c'Whether the entity is a character device.
    'd'Whether the entity is a directory.
    'e'Whether the entity is an existing entity.
    'f'Whether the entity is an existing regular file.
    'g'Whether the entity's setgid bit is set.
    'G'Whether the entity's group ownership is equal to the caller's.
    'k'Whether the entity's sticky bit is set.
    'l'Whether the entity is a symbolic link.
    'o'Whether the entity is owned by the caller's effective uid.
    'O'Like'o', but uses the real uid (not the effective uid).
    'p'Whether the entity is a FIFO device (named pipe).
    'r'Whether the entity is readable by the caller's effective uid/gid.
    'R'Like'r', but uses the real uid/gid (not the effective uid/gid).
    'S'Whether the entity is a socket.
    'u'Whether the entity's setuid bit is set.
    'w'Whether the entity is writable by the caller's effective uid/gid.
    'W'Like'w', but uses the real uid/gid (not the effective uid/gid).
    'x'Whether the entity is executable by the caller's effective uid/gid.
    'X'Like'x', but uses the real uid/gid (not the effective uid/git).
    'z'Whether the entity exists and is of length zero.
  • This test operates only on the entity atpath0, and returns an integer size ornil:

    CharacterTest
    's'Returns positive integer size if the entity exists and has non-zero length,nil otherwise.
  • Each of these tests operates only on the entity atpath0, and returns aTime object; raises an exception if the entity does not exist:

    CharacterTest
    'A'Last access time for the entity.
    'C'Last change time for the entity.
    'M'Last modification time for the entity.
  • Each of these tests operates on the modification time (mtime) of each of the entities atpath0 andpath1, and returns atrue orfalse; returnsfalse if either entity does not exist:

    CharacterTest
    '<'Whether themtime atpath0 is less than that atpath1.
    '='Whether themtime atpath0 is equal to that atpath1.
    '>'Whether themtime atpath0 is greater than that atpath1.
  • This test operates on the content of each of the entities atpath0 andpath1, and returns atrue orfalse; returnsfalse if either entity does not exist:

    CharacterTest
    '-'Whether the entities exist and are identical.
Source
# File kernel.rb, line 121defthenPrimitive.attr!:inline_blockunlessdefined?(yield)returnPrimitive.cexpr!'SIZED_ENUMERATOR(self, 0, 0, rb_obj_size)'endyield(self)end

Yields self to the block and returns the result of the block.

3.next.then {|x|x**x }.to_s#=> "256"

A good use ofthen is value piping in method chains:

require'open-uri'require'json'construct_url(arguments)  .then {|url|URI(url).read }  .then {|response|JSON.parse(response) }

When called without a block, the method returns anEnumerator, which can be used, for example, for conditional circuit-breaking:

# Meets condition, no-op1.then.detect(&:odd?)# => 1# Does not meet condition, drop value2.then.detect(&:odd?)# => nil
Also aliased as:yield_self
Source
static VALUErb_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);}

Transfers control to the end of the activecatch block waiting fortag. RaisesUncaughtThrowError if there is nocatch block for thetag. The optional second parameter supplies a return value for thecatch block, which otherwise defaults tonil. For examples, see Kernel::catch.

Source
static VALUEf_trace_var(int c, const VALUE *a, VALUE _){    return rb_f_trace_var(c, a);}

Controls tracing of assignments to global variables. The parametersymbol identifies the variable (as either a string name or a symbol identifier).cmd (which may be a string or aProc object) or block is executed whenever the variable is assigned. The block orProc object receives the variable’s new value as a parameter. Also seeuntrace_var.

trace_var:$_,proc {|v|puts"$_ is now '#{v}'" }$_ ="hello"$_ =' there'

produces:

$_ is now 'hello'$_ is now ' there'
Source
static VALUEsig_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);}

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: 27461Child diedTerminating: 27460
Source
static VALUEf_untrace_var(int c, const VALUE *a, VALUE _){    return rb_f_untrace_var(c, a);}

Removes tracing for the specified command on the given global variable and returnsnil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.

Source
# File warning.rb, line 52defwarn(*msgs,uplevel:nil,category:nil)ifPrimitive.cexpr!("NIL_P(category)")Primitive.rb_warn_m(msgs,uplevel,nil)elsifWarning[category =Primitive.cexpr!("rb_to_symbol_type(category)")]Primitive.rb_warn_m(msgs,uplevel,category)endend

If warnings have been disabled (for example with the-W0 flag), does nothing. Otherwise, converts each of the messages to strings, appends a newline character to the string if the string does not end in a newline, and callsWarning.warn with the string.

warn("warning 1","warning 2")

produces:

warning1warning2

If theuplevel keyword argument is given, the string will be prepended with information for the given caller frame in the same format used by therb_warn C function.

# In baz.rbdeffoowarn("invalid call to foo",uplevel:1)enddefbarfooendbar

produces:

baz.rb:6: warning: invalid call to foo

Ifcategory keyword argument is given, passes the category toWarning.warn. The category given must be one of the following categories:

:deprecated

Used for warning for deprecated functionality that may be removed in the future.

:experimental

Used for experimental features that may change in future releases.

:performance

Used for warning about APIs or pattern that have negative performance impact

Alias for:then

Private Instance Methods

Source
# File ext/json/lib/json/common.rb, line 1127defJSON(object,opts =nil)JSON[object,opts]end

Ifobject is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise, generate aJSON text from the Ruby data structure object and return it.

Theopts argument is passed through to generate/parse respectively. See generate and parse for their documentation.

Source
# File pathname_builtin.rb, line 1171defPathname(path)# :doc:returnpathifPathname===pathPathname.new(path)end

Creates aPathname object.

Source
# File lib/uri/common.rb, line 911defURI(uri)ifuri.is_a?(URI::Generic)urielsifuri =String.try_convert(uri)URI.parse(uri)elseraiseArgumentError,"bad argument (expected URI object or URI string)"endend

Returns a URI object derived from the givenuri, which may be a URI string or an existing URI object:

require'uri'# Returns a new URI.uri =URI('http://github.com/ruby/ruby')# => #<URI::HTTP http://github.com/ruby/ruby># Returns the given URI.URI(uri)# => #<URI::HTTP http://github.com/ruby/ruby>

You must require ‘uri’ to use this method.

Source
# File lib/rubygems/core_ext/kernel_gem.rb, line 35defgem(gem_name,*requirements)# :doc:skip_list = (ENV["GEM_SKIP"]||"").split(/:/)raiseGem::LoadError,"skipping #{gem_name}"ifskip_list.include?gem_nameifgem_name.is_a?Gem::DependencyunlessGem::Deprecate.skipwarn"#{Gem.location_of_caller.join ":"}:Warning: Kernel.gem no longer "\"accepts a Gem::Dependency object, please pass the name "\"and requirements directly"endrequirements =gem_name.requirementgem_name =gem_name.nameenddep =Gem::Dependency.new(gem_name,*requirements)loaded =Gem.loaded_specs[gem_name]returnfalseifloaded&&dep.matches_spec?(loaded)spec =dep.to_specifspecifGem::LOADED_SPECS_MUTEX.owned?spec.activateelseGem::LOADED_SPECS_MUTEX.synchronize {spec.activate }endendend

UseKernel#gem to activate a specific version ofgem_name.

requirements is a list of version requirements that the specified gem must match, most commonly “= example.version.number”. SeeGem::Requirement for how to specify a version requirement.

If you will be activating the latest version of a gem, there is no need to callKernel#gem,Kernel#require will do the right thing for you.

Kernel#gem returns true if the gem was activated, otherwise false. If the gem could not be found, didn’t match the version requirements, or a different version was already activated, an exception will be raised.

Kernel#gem should be calledbefore any require statements (otherwise RubyGems may load a conflicting library version).

Kernel#gem only loads prerelease versions when prereleaserequirements are given:

gem'rake','>= 1.1.a','< 2'

In older RubyGems versions, the environment variable GEM_SKIP could be used to skip activation of specified gems, for example to test out changes that haven’t been installed yet. Now RubyGems defers to -I and the RUBYLIB environment variable to skip activation of a gem.

Example:

GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb
Source
# File ext/json/lib/json/common.rb, line 1093defj(*objs)ifRUBY_VERSION>="3.0"warn"Kernel#j is deprecated and will be removed in json 3.0.0",uplevel:1,category::deprecatedelsewarn"Kernel#j is deprecated and will be removed in json 3.0.0",uplevel:1endobjs.eachdo|obj|putsJSON.generate(obj,:allow_nan=>true,:max_nesting=>false)endnilend

Outputsobjs to STDOUT asJSON strings in the shortest form, that is in one line.

Source
# File ext/json/lib/json/common.rb, line 1108defjj(*objs)ifRUBY_VERSION>="3.0"warn"Kernel#jj is deprecated and will be removed in json 3.0.0",uplevel:1,category::deprecatedelsewarn"Kernel#jj is deprecated and will be removed in json 3.0.0",uplevel:1endobjs.eachdo|obj|putsJSON.pretty_generate(obj,:allow_nan=>true,:max_nesting=>false)endnilend

Outputsobjs to STDOUT asJSON strings in a pretty format, with indentation and over many lines.

Source
# File lib/pp.rb, line 731defpp(*objs)objs.each {|obj|PP.pp(obj)  }objs.size<=1?objs.first:objsend

prints arguments in pretty form.

pp returns argument(s).

Source
# File lib/rubygems/core_ext/kernel_require.rb, line 36defrequire(path)# :doc:returngem_original_require(path)unlessGem.discover_gems_on_requireRUBYGEMS_ACTIVATION_MONITOR.synchronizedopath =File.path(path)# If +path+ belongs to a default gem, we activate it and then go straight# to normal requireifspec =Gem.find_default_spec(path)name =spec.namenextifGem.loaded_specs[name]# Ensure -I beats a default gemresolved_path =beginrp =nilload_path_check_index =Gem.load_path_insert_index-Gem.activated_gem_pathsGem.suffixes.finddo|s|$LOAD_PATH[0...load_path_check_index].finddo|lp|ifFile.symlink?lp# for backward compatibilitynextendfull_path =File.expand_path(File.join(lp,"#{path}#{s}"))rp =full_pathifFile.file?(full_path)endendrpendnextifresolved_pathKernel.send(:gem,name,Gem::Requirement.default_prerelease)Gem.load_bundler_extensions(Gem.loaded_specs[name].version)ifname=="bundler"nextend# If there are no unresolved deps, then we can use just try# normal require handle loading a gem from the rescue below.ifGem::Specification.unresolved_deps.empty?nextend# If +path+ is for a gem that has already been loaded, don't# bother trying to find it in an unresolved gem, just go straight# to normal require.#--# TODO request access to the C implementation of this to speed up RubyGemsifGem::Specification.find_active_stub_by_path(path)nextend# Attempt to find +path+ in any unresolved gems...found_specs =Gem::Specification.find_in_unresolvedpath# If there are no directly unresolved gems, then try and find +path+# in any gems that are available via the currently unresolved gems.# For example, given:##   a => b => c => d## If a and b are currently active with c being unresolved and d.rb is# requested, then find_in_unresolved_tree will find d.rb in d because# it's a dependency of c.#iffound_specs.empty?found_specs =Gem::Specification.find_in_unresolved_treepathfound_specs.each(&:activate)# We found +path+ directly in an unresolved gem. Now we figure out, of# the possible found specs, which one we should activate.else# Check that all the found specs are just different# versions of the same gemnames =found_specs.map(&:name).uniqifnames.size>1raiseGem::LoadError,"#{path} found in multiple gems: #{names.join ", "}"end# Ok, now find a gem that has no conflicts, starting# at the highest version.valid =found_specs.find {|s|!s.has_conflicts? }unlessvalidle =Gem::LoadError.new"unable to find a version of '#{names.first}' to activate"le.name =names.firstraiseleendvalid.activateendendbegingem_original_require(path)rescueLoadError=>load_errorifload_error.path==path&&RUBYGEMS_ACTIVATION_MONITOR.synchronize {Gem.try_activate(path) }returngem_original_require(path)endraiseload_errorendend

When RubyGems is required,Kernel#require is replaced with our own which is capable of loading gems on demand.

When you callrequire 'x', this is what happens:

  • If the file can be loaded from the existing Ruby loadpath, it is.

  • Otherwise, installed gems are searched for a file that matches. If it’s found in gem ‘y’, that gem is activated (added to the loadpath).

The normalrequire functionality of returning false if that file has already been loaded is preserved.

Source
# File ext/psych/lib/psych/y.rb, line 5defy*objectsputsPsych.dump_stream(*objects)end

An alias forPsych.dump_stream meant to be used with IRB.