Module: Kernel

Included in:
Object
Defined in:
object.c

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol[, *args]) ⇒ Object

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

class Roman
  def romanToInt(str)
    # ...
  end
  def method_missing(methId)
    str = methId.id2name
    romanToInt(str)
  end
end

r = Roman.new
r.iv      #=> 4
r.xxiii   #=> 23
r.mm      #=> 2000


# File 'eval.c'

/*
 *  call-seq:
 *     obj.method_missing(symbol [, *args] )   => result
 *  
 *  Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
 *  <i>symbol</i> is the symbol for the method called, and <i>args</i>
 *  are any arguments that were passed to it. By default, the interpreter
 *  raises an error when this method is called. However, it is possible
 *  to override the method to provide more dynamic behavior.
 *  The example below creates
 *  a class <code>Roman</code>, which responds to methods with names
 *  consisting of roman numerals, returning the corresponding integer
 *  values.
 *     
 *     class Roman
 *       def romanToInt(str)
 *         # ...
 *       end
 *       def method_missing(methId)
 *         str = methId.id2name
 *         romanToInt(str)
 *       end
 *     end
 *     
 *     r = Roman.new
 *     r.iv      #=> 4
 *     r.xxiii   #=> 23
 *     r.mm      #=> 2000
 */

static VALUE
rb_method_missing(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    ID id;
    VALUE exc = rb_eNoMethodError;
    const char *format = 0;
    NODE *cnode = ruby_current_node;

    if (argc == 0 || !SYMBOL_P(argv[0])) {
    rb_raise(rb_eArgError, "no id given");
    }

    stack_check();

    id = SYM2ID(argv[0]);

    if (last_call_status & CSTAT_PRIV) {
    format = "private method `%s' called for %s";
    }
    else if (last_call_status & CSTAT_PROT) {
    format = "protected method `%s' called for %s";
    }
    else if (last_call_status & CSTAT_VCALL) {
    format = "undefined local variable or method `%s' for %s";
    exc = rb_eNameError;
    }
    else if (last_call_status & CSTAT_SUPER) {
    format = "super: no superclass method `%s' for %s";
    }
    if (!format) {
    format = "undefined method `%s' for %s";
    }

    ruby_current_node = cnode;
    {
    int n = 0;
    VALUE args[3];

    args[n++] = rb_funcall(rb_const_get(exc, rb_intern("message")), '!',
                   3, rb_str_new2(format), obj, argv[0]);
    args[n++] = argv[0];
    if (exc == rb_eNoMethodError) {
        args[n++] = rb_ary_new4(argc-1, argv+1);
    }
    exc = rb_class_new_instance(n, args, exc);
    ruby_frame = ruby_frame->prev; /* pop frame for "method_missing" */
    rb_exc_raise(exc);
    }

    return Qnil;        /* not reached */
}

Instance Method Details

#__method__Object

Returns the name of the current method as a Symbol. If called from inside of an aliased method it will return the original nonaliased name. If called outside of a method, it returns nil.

def foo
  __method__
end
alias bar foo

foo                # => :foo
bar                # => :foo


# File 'eval.c'

/*
 *  call-seq:
 *     __method__         => symbol
 *  
 *  Returns the name of the current method as a Symbol.
 *  If called from inside of an aliased method it will return the original
 *  nonaliased name.
 *  If called outside of a method, it returns <code>nil</code>.
 *  
 *    def foo
 *      __method__
 *    end
 *    alias bar foo
 *    
 *    foo                # => :foo
 *    bar                # => :foo
 *
 */

static VALUE
rb_f_method_name()
{
    struct FRAME* prev = ruby_frame->prev;
    if (prev && prev->orig_func) {
    return ID2SYM(prev->orig_func);
    }
    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:



# File 'io.c'

/*
 *  call-seq:
 *     `cmd`    => string
 *  
 *  Returns the standard output of running _cmd_ in a subshell.
 *  The built-in syntax <code>%x{...}</code> uses
 *  this method. Sets <code>$?</code> 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
 */

static VALUE
rb_f_backquote(obj, str)
    VALUE obj, str;
{
    volatile VALUE port;
    VALUE result;
    rb_io_t *fptr;

    SafeStringValue(str);
    port = pipe_open(str, 0, "r");
    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);

    return result;
}

#abortObject #Kernel::abortObject #Process::abortObject

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



# File 'eval.c'

/*
 *  call-seq:
 *     abort
 *     Kernel::abort
 *     Process::abort
 *  
 *  Terminate execution immediately, effectively by calling
 *  <code>Kernel.exit(1)</code>. If _msg_ is given, it is written
 *  to STDERR prior to terminating.
 */

VALUE
rb_f_abort(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_secure(4);
    if (argc == 0) {
    if (!NIL_P(ruby_errinfo)) {
        error_print();
    }
    rb_exit(EXIT_FAILURE);
    }
    else {
    VALUE mesg;

    rb_scan_args(argc, argv, "1", &mesg);
    StringValue(mesg);
    rb_io_puts(1, &mesg, rb_stderr);
    terminate_process(EXIT_FAILURE, mesg);
    }
    return Qnil;        /* not reached */
}

#Array(arg) ⇒ Array

Returns arg as an Array. First tries to call arg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg (unless arg is nil).

Array(1..5)   #=> [1, 2, 3, 4, 5]

Returns:



# File 'object.c'

/*
 *  call-seq:
 *     Array(arg)    => array
 *  
 *  Returns <i>arg</i> as an <code>Array</code>. First tries to call
 *  <i>arg</i><code>.to_ary</code>, then <i>arg</i><code>.to_a</code>.
 *  If both fail, creates a single element array containing <i>arg</i>
 *  (unless <i>arg</i> is <code>nil</code>).
 *     
 *     Array(1..5)   #=> [1, 2, 3, 4, 5]
 */

static VALUE
rb_f_array(obj, arg)
    VALUE obj, 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:



# File 'eval.c'

/*
 *  call-seq:
 *     at_exit { block } -> 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
 *     
 *  <em>produces:</em>
 *     
 *     goodbye cruel world
 */

static VALUE
rb_f_at_exit()
{
    VALUE proc;

    if (!rb_block_given_p()) {
    rb_raise(rb_eArgError, "called without a block");
    }
    proc = rb_block_proc();
    rb_set_end_proc(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)


# File 'eval.c'

/*
 *  call-seq:
 *     autoload(module, filename)   => nil
 *  
 *  Registers _filename_ to be loaded (using <code>Kernel::require</code>) 
 *  the first time that _module_ (which may be a <code>String</code> or
 *  a symbol) is accessed.
 *     
 *     autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
 */

static VALUE
rb_f_autoload(obj, sym, file)
    VALUE obj;
    VALUE sym;
    VALUE file;
{
    if (NIL_P(ruby_cbase)) {
    rb_raise(rb_eTypeError, "no class/module for autoload target");
    }
    return rb_mod_autoload(ruby_cbase, sym, file);
}

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


# File 'eval.c'

/*
 *  call-seq:
 *     autoload(module, filename)   => nil
 *
 *  Registers _filename_ to be loaded (using <code>Kernel::require</code>)
 *  the first time that _module_ (which may be a <code>String</code> or
 *  a symbol) is accessed.
 *
 *     autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
 */

static VALUE
rb_f_autoload_p(obj, sym)
    VALUE obj;
    VALUE sym;
{
    /* use ruby_cbase as same as rb_f_autoload. */
    if (NIL_P(ruby_cbase)) {
    return Qfalse;
    }
    return rb_mod_autoload_p(ruby_cbase, sym);
}

#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. Also see the description of class Binding.

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

Returns:



# File 'eval.c'

/*
 *  call-seq:
 *     binding -> a_binding
 *  
 *  Returns a +Binding+ object, describing the variable and
 *  method bindings at the point of call. This object can be used when
 *  calling +eval+ to execute the evaluated command in this
 *  environment. Also see the description of class +Binding+.
 *     
 *     def getBinding(param)
 *       return binding
 *     end
 *     b = getBinding("hello")
 *     eval("param", b)   #=> "hello"
 */

static VALUE
rb_f_binding(self)
    VALUE self;
{
    struct BLOCK *data, *p;
    struct RVarmap *vars;
    VALUE bind;

    PUSH_BLOCK(0,0);
    bind = Data_Make_Struct(rb_cBinding,struct BLOCK,blk_mark,blk_free,data);
    *data = *ruby_block;

    data->orig_thread = rb_thread_current();
    data->wrapper = ruby_wrapper;
    data->iter = rb_f_block_given_p();
    frame_dup(&data->frame);
    if (ruby_frame->prev) {
    data->frame.last_func = ruby_frame->prev->last_func;
    data->frame.last_class = ruby_frame->prev->last_class;
    data->frame.orig_func = ruby_frame->prev->orig_func;
    }

    if (data->iter) {
    blk_copy_prev(data);
    }
    else {
    data->prev = 0;
    }

    for (p = data; p; p = p->prev) {
    for (vars = p->dyna_vars; vars; vars = vars->next) {
        if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
        FL_SET(vars, DVAR_DONT_RECYCLE);
    }
    }
    scope_dup(data->scope);
    POP_BLOCK();

    return bind;
}

#block_given?Boolean #iterator?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"

Overloads:

  • #block_given?Boolean

    Returns:

    • (Boolean)
  • #iterator?Boolean

    Returns:

    • (Boolean)


# File 'eval.c'

/*
 *  call-seq:
 *     block_given?   => true or false
 *     iterator?      => true or false
 *  
 *  Returns <code>true</code> if <code>yield</code> would execute a
 *  block in the current context. The <code>iterator?</code> 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"
 */


static VALUE
rb_f_block_given_p()
{
    if (ruby_frame->prev && ruby_frame->prev->iter == ITER_CUR && ruby_block)
    return Qtrue;
    return Qfalse;
}

#callcc {|cont| ... } ⇒ Object

Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. See class Continuation for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.

Yields:

  • (cont)

Returns:



# File 'eval.c'

/*
 *  call-seq:
 *     callcc {|cont| block }   =>  obj
 *  
 *  Generates a <code>Continuation</code> object, which it passes to the
 *  associated block. Performing a <em>cont</em><code>.call</code> will
 *  cause the <code>callcc</code> to return (as will falling through the
 *  end of the block). The value returned by the <code>callcc</code> is
 *  the value of the block, or the value passed to
 *  <em>cont</em><code>.call</code>. See class <code>Continuation</code> 
 *  for more details. Also see <code>Kernel::throw</code> for
 *  an alternative mechanism for unwinding a call stack.
 */

static VALUE
rb_callcc(self)
    VALUE self;
{
    volatile VALUE cont;
    rb_thread_t th;
    volatile rb_thread_t th_save;
    struct tag *tag;
    struct RVarmap *vars;

    THREAD_ALLOC(th);
    /* must finish th initialization before any possible gc.
     * [email protected] */
    th->thread = curr_thread->thread;
    th->thgroup = cont_protect;
    cont = Data_Wrap_Struct(rb_cCont, cc_mark, thread_free, th);

    scope_dup(ruby_scope);
    for (tag=prot_tag; tag; tag=tag->prev) {
    scope_dup(tag->scope);
    }

    for (vars = ruby_dyna_vars; vars; vars = vars->next) {
    if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
    FL_SET(vars, DVAR_DONT_RECYCLE);
    }
    th_save = th;
    if (THREAD_SAVE_CONTEXT(th)) {
    return th_save->result;
    }
    else {
    return rb_yield(cont);
    }
}

#caller(start = 1) ⇒ 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 result.

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"]
c(1)   #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
c(2)   #=> ["prog:8:in `c'", "prog:12"]
c(3)   #=> ["prog:13"]

Returns:



# File 'eval.c'

/*
 *  call-seq:
 *     caller(start=1)    => array
 *  
 *  Returns the current execution stack---an array containing strings in
 *  the form ``<em>file:line</em>'' or ``<em>file:line: in
 *  `method'</em>''. The optional _start_ parameter
 *  determines the number of initial stack entries to omit from the
 *  result.
 *     
 *     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"]
 *     c(1)   #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
 *     c(2)   #=> ["prog:8:in `c'", "prog:12"]
 *     c(3)   #=> ["prog:13"]
 */

static VALUE
rb_f_caller(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE level;
    int lev;

    rb_scan_args(argc, argv, "01", &level);

    if (NIL_P(level)) lev = 1;
    else lev = NUM2INT(level);
    if (lev < 0) rb_raise(rb_eArgError, "negative level (%d)", lev);

    return backtrace(lev);
}

#catch(symbol) ⇒ Object

catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw???s symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.

def routine(n)
  puts n
  throw :done if n <= 0
  routine(n-1)
end

catch(:done) { routine(3) }

produces:

3
2
1
0


# File 'eval.c'

/*
 *  call-seq:
 *     catch(symbol) {| | block }  > obj
 *  
 *  +catch+ executes its block. If a +throw+ is
 *  executed, Ruby searches up its stack for a +catch+ block
 *  with a tag corresponding to the +throw+'s
 *  _symbol_. If found, that block is terminated, and
 *  +catch+ returns the value given to +throw+. If
 *  +throw+ is not called, the block terminates normally, and
 *  the value of +catch+ is the value of the last expression
 *  evaluated. +catch+ expressions may be nested, and the
 *  +throw+ call need not be in lexical scope.
 *     
 *     def routine(n)
 *       puts n
 *       throw :done if n <= 0
 *       routine(n-1)
 *     end
 *     
 *     
 *     catch(:done) { routine(3) }
 *     
 *  <em>produces:</em>
 *     
 *     3
 *     2
 *     1
 *     0
 */

static VALUE
rb_f_catch(dmy, tag)
    VALUE dmy, tag;
{
    int state;
    VALUE val = Qnil;       /* OK */

    tag = ID2SYM(rb_to_id(tag));
    PUSH_TAG(tag);
    if ((state = EXEC_TAG()) == 0) {
    val = rb_yield_0(tag, 0, 0, 0, Qfalse);
    }
    else if (state == TAG_THROW && tag == prot_tag->dst) {
    val = prot_tag->retval;
    state = 0;
    }
    POP_TAG();
    if (state) JUMP_TAG(state);

    return val;
}

#chompObject #chomp(string) ⇒ Object

Equivalent to $_ = $_.chomp(string). See String#chomp.

$_ = "now\n"
chomp         #=> "now"
$_            #=> "now"
chomp "ow"    #=> "n"
$_            #=> "n"
chomp "xxx"   #=> "n"
$_            #=> "n"


# File 'string.c'

/*
 *  call-seq:
 *     chomp            => $_
 *     chomp(string)    => $_
 *  
 *  Equivalent to <code>$_ = $_.chomp(<em>string</em>)</code>. See
 *  <code>String#chomp</code>.
 *     
 *     $_ = "now\n"
 *     chomp         #=> "now"
 *     $_            #=> "now"
 *     chomp "ow"    #=> "n"
 *     $_            #=> "n"
 *     chomp "xxx"   #=> "n"
 *     $_            #=> "n"
 */

static VALUE
rb_f_chomp(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str = uscore_get();
    VALUE dup = rb_str_dup(str);

    if (NIL_P(rb_str_chomp_bang(argc, argv, dup)))
    return str;
    rb_lastline_set(dup);
    return dup;
}

#chomp!nil #chomp!(string) ⇒ nil

Equivalent to $_.chomp!(string). See String#chomp!

$_ = "now\n"
chomp!       #=> "now"
$_           #=> "now"
chomp! "x"   #=> nil
$_           #=> "now"

Overloads:

  • #chomp!nil

    Returns:

    • (nil)
  • #chomp!(string) ⇒ nil

    Returns:

    • (nil)


# File 'string.c'

/*
 *  call-seq:
 *     chomp!             => $_ or nil
 *     chomp!(string)     => $_ or nil
 *  
 *  Equivalent to <code>$_.chomp!(<em>string</em>)</code>. See
 *  <code>String#chomp!</code>
 *     
 *     $_ = "now\n"
 *     chomp!       #=> "now"
 *     $_           #=> "now"
 *     chomp! "x"   #=> nil
 *     $_           #=> "now"
 */

static VALUE
rb_f_chomp_bang(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_chomp_bang(argc, argv, uscore_get());
}

#chopString

Equivalent to ($_.dup).chop!, except nil is never returned. See String#chop!.

a  =  "now\r\n"
$_ = a
chop   #=> "now"
$_     #=> "now"
chop   #=> "no"
chop   #=> "n"
chop   #=> ""
chop   #=> ""
a      #=> "now\r\n"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     chop   => string
 *  
 *  Equivalent to <code>($_.dup).chop!</code>, except <code>nil</code>
 *  is never returned. See <code>String#chop!</code>.
 *     
 *     a  =  "now\r\n"
 *     $_ = a
 *     chop   #=> "now"
 *     $_     #=> "now"
 *     chop   #=> "no"
 *     chop   #=> "n"
 *     chop   #=> ""
 *     chop   #=> ""
 *     a      #=> "now\r\n"
 */

static VALUE
rb_f_chop()
{
    VALUE str = uscore_get();

    if (RSTRING(str)->len > 0) {
    str = rb_str_dup(str);
    rb_str_chop_bang(str);
    rb_lastline_set(str);
    }
    return str;
}

#chop!nil

Equivalent to $_.chop!.

a  = "now\r\n"
$_ = a
chop!   #=> "now"
chop!   #=> "no"
chop!   #=> "n"
chop!   #=> ""
chop!   #=> nil
$_      #=> ""
a       #=> ""

Returns:

  • (nil)


# File 'string.c'

/*
 *  call-seq:
 *     chop!    => $_ or nil
 *  
 *  Equivalent to <code>$_.chop!</code>.
 *     
 *     a  = "now\r\n"
 *     $_ = a
 *     chop!   #=> "now"
 *     chop!   #=> "no"
 *     chop!   #=> "n"
 *     chop!   #=> ""
 *     chop!   #=> nil
 *     $_      #=> ""
 *     a       #=> ""
 */

static VALUE
rb_f_chop_bang(str)
    VALUE str;
{
    return rb_str_chop_bang(uscore_get());
}

#eval(string[, binding [, filename [,lineno]]]) ⇒ Object

Evaluates the Ruby expression(s) in string. If binding is given, the evaluation is performed in its context. The binding may be a Binding object or a Proc object. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.

def getBinding(str)
  return binding
end
str = "hello"
eval "str + ' Fred'"                      #=> "hello Fred"
eval "str + ' Fred'", getBinding("bye")   #=> "bye Fred"

Returns:



# File 'eval.c'

/*
 *  call-seq:
 *     eval(string [, binding [, filename [,lineno]]])  => obj
 *  
 *  Evaluates the Ruby expression(s) in <em>string</em>. If
 *  <em>binding</em> is given, the evaluation is performed in its
 *  context. The binding may be a <code>Binding</code> object or a
 *  <code>Proc</code> object. If the optional <em>filename</em> and
 *  <em>lineno</em> parameters are present, they will be used when
 *  reporting syntax errors.
 *     
 *     def getBinding(str)
 *       return binding
 *     end
 *     str = "hello"
 *     eval "str + ' Fred'"                      #=> "hello Fred"
 *     eval "str + ' Fred'", getBinding("bye")   #=> "bye Fred"
 */

static VALUE
rb_f_eval(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE src, scope, vfile, vline;
    const char *file = "(eval)";
    int line = 1;

    rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
    if (ruby_safe_level >= 4) {
    StringValue(src);
    if (!NIL_P(scope) && !OBJ_TAINTED(scope)) {
        rb_raise(rb_eSecurityError, "Insecure: can't modify trusted binding");
    }
    }
    else {
    SafeStringValue(src);
    }
    if (argc >= 3) {
    StringValue(vfile);
    }
    if (argc >= 4) {
    line = NUM2INT(vline);
    }

    if (!NIL_P(vfile)) file = RSTRING(vfile)->ptr;
    if (NIL_P(scope) && ruby_frame->prev) {
    struct FRAME *prev;
    VALUE val;

    prev = ruby_frame;
    PUSH_FRAME();
    *ruby_frame = *prev->prev;
    ruby_frame->prev = prev;
    val = eval(self, src, scope, file, line);
    POP_FRAME();

    return val;
    }
    return eval(self, src, scope, file, line);
}

#exec(command[, arg, ...]) ⇒ Object

Replaces the current process by running the given external command. If exec is given a single argument, that argument is taken as a line that is subject to shell expansion before being executed. If multiple arguments are given, the second and subsequent arguments are passed as parameters to command with no shell expansion. If the first argument is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).

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

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


# File 'process.c'

/*
 *  call-seq:
 *     exec(command [, arg, ...])
 *
 *  Replaces the current process by running the given external _command_.
 *  If +exec+ is given a single argument, that argument is
 *  taken as a line that is subject to shell expansion before being
 *  executed. If multiple arguments are given, the second and subsequent
 *  arguments are passed as parameters to _command_ with no shell
 *  expansion. If the first argument is a two-element array, the first
 *  element is the command to be executed, and the second argument is
 *  used as the <code>argv[0]</code> value, which may show up in process
 *  listings. In MSDOS environments, the command is executed in a
 *  subshell; otherwise, one of the <code>exec(2)</code> system calls is
 *  used, so the running command may inherit some of the environment of
 *  the original program (including open file descriptors).
 *
 *     exec "echo *"       # echoes list of files in current directory
 *     # never get here
 *
 *
 *     exec "echo", "*"    # echoes an asterisk
 *     # never get here
 */

VALUE
rb_f_exec(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE prog = 0;
    VALUE tmp;
    struct rb_exec_arg earg;

    if (argc == 0) {
    rb_last_status = Qnil;
    rb_raise(rb_eArgError, "wrong number of arguments");
    }

    tmp = rb_check_array_type(argv[0]);
    if (!NIL_P(tmp)) {
    if (RARRAY(tmp)->len != 2) {
        rb_raise(rb_eArgError, "wrong first argument");
    }
    prog = RARRAY(tmp)->ptr[0];
    argv[0] = RARRAY(tmp)->ptr[1];
    SafeStringValue(prog);
    }
    proc_prepare_args(&earg, argc, argv, prog);
    proc_exec_args((VALUE)&earg);
    rb_sys_fail(RSTRING(argv[0])->ptr);
    return Qnil;        /* dummy */
}

#exit(integer = 0) ⇒ Object #Kernel::exit(integer = 0) ⇒ Object #Process::exit(integer = 0) ⇒ 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.

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


# File 'eval.c'

/*
 *  call-seq:
 *     exit(integer=0)
 *     Kernel::exit(integer=0)
 *     Process::exit(integer=0)
 *  
 *  Initiates the termination of the Ruby script by raising the
 *  <code>SystemExit</code> exception. This exception may be caught. The
 *  optional parameter is used to return a status code to the invoking
 *  environment.
 *     
 *     begin
 *       exit
 *       puts "never get here"
 *     rescue SystemExit
 *       puts "rescued a SystemExit exception"
 *     end
 *     puts "after begin block"
 *     
 *  <em>produces:</em>
 *     
 *     rescued a SystemExit exception
 *     after begin block
 *     
 *  Just prior to termination, Ruby executes any <code>at_exit</code> 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
 *     
 *  <em>produces:</em>
 *     
 *     at_exit function
 *     in finalizer
 */

VALUE
rb_f_exit(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE status;
    int istatus;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &status) == 1) {
    switch (status) {
      case Qtrue:
        istatus = EXIT_SUCCESS;
        break;
      case Qfalse:
        istatus = EXIT_FAILURE;
        break;
      default:
        istatus = NUM2INT(status);
#if EXIT_SUCCESS != 0
        if (istatus == 0) istatus = EXIT_SUCCESS;
#endif
        break;
    }
    }
    else {
    istatus = EXIT_SUCCESS;
    }
    rb_exit(istatus);
    return Qnil;        /* not reached */
}

#exit!(fixnum = -1) ⇒ Object

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

Process.exit!(0)


# File 'process.c'

/*
 *  call-seq:
 *     Process.exit!(fixnum=-1)
 *
 *  Exits the process immediately. No exit handlers are
 *  run. <em>fixnum</em> is returned to the underlying system as the
 *  exit status.
 *
 *     Process.exit!(0)
 */

static VALUE
rb_f_exit_bang(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE status;
    int istatus;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &status) == 1) {
    switch (status) {
      case Qtrue:
        istatus = EXIT_SUCCESS;
        break;
      case Qfalse:
        istatus = EXIT_FAILURE;
        break;
      default:
        istatus = NUM2INT(status);
        break;
    }
    }
    else {
    istatus = EXIT_FAILURE;
    }
    _exit(istatus);

    return Qnil;        /* not reached */
}

#raiseObject #raise(string) ⇒ Object #raise(exception[, string [, array]]) ⇒ Object #failObject #fail(string) ⇒ Object #fail(exception[, string [, array]]) ⇒ 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 the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller


# File 'eval.c'

/*
 *  call-seq:
 *     raise
 *     raise(string)
 *     raise(exception [, string [, array]])
 *     fail
 *     fail(string)
 *     fail(exception [, string [, array]])
 *  
 *  With no arguments, raises the exception in <code>$!</code> or raises
 *  a <code>RuntimeError</code> if <code>$!</code> is +nil+.
 *  With a single +String+ argument, raises a
 *  +RuntimeError+ with the string as a message. Otherwise,
 *  the first parameter should be the name of an +Exception+
 *  class (or an object that returns an +Exception+ object when sent
 *  an +exception+ message). The optional second parameter sets the
 *  message associated with the exception, and the third parameter is an
 *  array of callback information. Exceptions are caught by the
 *  +rescue+ clause of <code>begin...end</code> blocks.
 *     
 *     raise "Failed to create socket"
 *     raise ArgumentError, "No parameters", caller
 */

static VALUE
rb_f_raise(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_raise_jump(rb_make_exception(argc, argv));
    return Qnil;        /* not reached */
}

#Float(arg) ⇒ Float

Returns arg converted to a float. Numeric types are converted directly, the rest are converted using arg.to_f. As of Ruby 1.8, converting nil generates a TypeError.

Float(1)           #=> 1.0
Float("123.456")   #=> 123.456

Returns:



# File 'object.c'

/*
 *  call-seq:
 *     Float(arg)    => float
 *  
 *  Returns <i>arg</i> converted to a float. Numeric types are converted
 *  directly, the rest are converted using <i>arg</i>.to_f. As of Ruby
 *  1.8, converting <code>nil</code> generates a <code>TypeError</code>.
 *     
 *     Float(1)           #=> 1.0
 *     Float("123.456")   #=> 123.456
 */

static VALUE
rb_f_float(obj, arg)
    VALUE obj, arg;
{
    return rb_Float(arg);
}

#fork { ... } ⇒ Fixnum? #fork { ... } ⇒ Fixnum?

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.

Overloads:



# File 'process.c'

/*
 *  call-seq:
 *     Kernel.fork  [{ block }]   => fixnum or nil
 *     Process.fork [{ block }]   => fixnum or nil
 *
 *  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
 *  <code>Kernel.exit!</code> to avoid running any
 *  <code>at_exit</code> functions. The parent process should
 *  use <code>Process.wait</code> to collect the termination statuses
 *  of its children or use <code>Process.detach</code> 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.
 */

static VALUE
rb_f_fork(obj)
    VALUE obj;
{
#if !defined(__human68k__) && !defined(_WIN32) && !defined(__MACOS__) && !defined(__EMX__) && !defined(__VMS)
    int pid;

    rb_secure(2);

#ifndef __VMS
    fflush(stdout);
    fflush(stderr);
#endif

    before_exec();
    pid = fork();
    after_exec();

    switch (pid) {
      case 0:
#ifdef linux
    after_exec();
#endif
    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 INT2FIX(pid);
    }
#else
    rb_notimplement();
#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. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

Flag     | Applies to   | Meaning
---------+--------------+-----------------------------------------
space    | bdeEfgGiouxX | Leave a space at the start of
         |              | positive numbers.
---------+--------------+-----------------------------------------
(digit)$ | all          | Specifies the absolute argument number
         |              | for this field. Absolute and relative
         |              | argument numbers cannot be mixed in a
         |              | sprintf string.
---------+--------------+-----------------------------------------
 #       | beEfgGoxX    | Use an alternative format. For the
         |              | conversions `o', `x', `X', and `b',
         |              | prefix the result with ``0'', ``0x'', ``0X'',
         |              |  and ``0b'', respectively. For `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.
---------+--------------+-----------------------------------------
+        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
---------+--------------+-----------------------------------------
-        | all          | Left-justify the result of this conversion.
---------+--------------+-----------------------------------------
0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
---------+--------------+-----------------------------------------
*        | 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.

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

The field types are:

Field |  Conversion
------+--------------------------------------------------------------
  b   | Convert argument as a binary number.
  c   | Argument is the numeric code for a single character.
  d   | Convert argument as a decimal number.
  E   | Equivalent to `e', but uses an uppercase E to indicate
      | the exponent.
  e   | Convert floating point argument into exponential notation
      | with one digit before the decimal point. The precision
      | determines the number of fractional digits (defaulting to six).
  f   | Convert floating point argument as [-]ddd.ddd,
      |  where the precision determines the number of digits after
      | the decimal point.
  G   | Equivalent to `g', but use an uppercase `E' in exponent form.
  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 d.dddd form otherwise.
  i   | Identical to `d'.
  o   | Convert argument as an octal number.
  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.
  u   | Treat argument as an unsigned decimal number. Negative integers
      | are displayed as a 32 bit two's complement plus one for the
      | underlying architecture; that is, 2 ** 32 + n.  However, since
      | Ruby has no inherent limit on bits used to represent the
      | integer, this value is preceded by two dots (..) in order to
      | indicate a infinite number of leading sign bits.
  X   | Convert argument as a hexadecimal number using uppercase
      | letters. Negative numbers will be displayed with two
      | leading periods (representing an infinite string of
      | leading 'FF's.
  x   | Convert argument as a hexadecimal number.
      | Negative numbers will be displayed with two
      | leading periods (representing an infinite string of
      | leading 'ff's.

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)                        #=> "..4294967173"

Overloads:

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

    Returns:

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

    Returns:



# File 'object.c'

/*
 *  call-seq:
 *     format(format_string [, arguments...] )   => string
 *     sprintf(format_string [, arguments...] )  => string
 *  
 *  Returns the string resulting from applying <i>format_string</i> to
 *  any additional arguments. Within the format string, any characters
 *  other than format sequences are copied to the result. A format
 *  sequence consists of a percent sign, followed by optional flags,
 *  width, and precision indicators, then terminated with a field type
 *  character. The field type controls how the corresponding
 *  <code>sprintf</code> argument is to be interpreted, while the flags
 *  modify that interpretation. The field type characters are listed
 *  in the table at the end of this section. The flag characters are:
 *
 *    Flag     | Applies to   | Meaning
 *    ---------+--------------+-----------------------------------------
 *    space    | bdeEfgGiouxX | Leave a space at the start of 
 *             |              | positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    (digit)$ | all          | Specifies the absolute argument number
 *             |              | for this field. Absolute and relative
 *             |              | argument numbers cannot be mixed in a
 *             |              | sprintf string.
 *    ---------+--------------+-----------------------------------------
 *     #       | beEfgGoxX    | Use an alternative format. For the
 *             |              | conversions `o', `x', `X', and `b', 
 *             |              | prefix the result with ``0'', ``0x'', ``0X'',
 *             |              |  and ``0b'', respectively. For `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.
 *    ---------+--------------+-----------------------------------------
 *    +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    -        | all          | Left-justify the result of this conversion.
 *    ---------+--------------+-----------------------------------------
 *    0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
 *    ---------+--------------+-----------------------------------------
 *    *        | 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.
 *
 *     
 *  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. 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 <code>%10.10s</code> will always contribute exactly ten
 *  characters to the result.)
 *
 *  The field types are:
 *
 *      Field |  Conversion
 *      ------+--------------------------------------------------------------
 *        b   | Convert argument as a binary number.
 *        c   | Argument is the numeric code for a single character.
 *        d   | Convert argument as a decimal number.
 *        E   | Equivalent to `e', but uses an uppercase E to indicate
 *            | the exponent.
 *        e   | Convert floating point argument into exponential notation 
 *            | with one digit before the decimal point. The precision
 *            | determines the number of fractional digits (defaulting to six).
 *        f   | Convert floating point argument as [-]ddd.ddd, 
 *            |  where the precision determines the number of digits after
 *            | the decimal point.
 *        G   | Equivalent to `g', but use an uppercase `E' in exponent form.
 *        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 d.dddd form otherwise.
 *        i   | Identical to `d'.
 *        o   | Convert argument as an octal number.
 *        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.
 *        u   | Treat argument as an unsigned decimal number. Negative integers
 *            | are displayed as a 32 bit two's complement plus one for the
 *            | underlying architecture; that is, 2 ** 32 + n.  However, since
 *            | Ruby has no inherent limit on bits used to represent the
 *            | integer, this value is preceded by two dots (..) in order to
 *            | indicate a infinite number of leading sign bits.
 *        X   | Convert argument as a hexadecimal number using uppercase
 *            | letters. Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'FF's.
 *        x   | Convert argument as a hexadecimal number.
 *            | Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'ff's.
 *     
 *  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)                        #=> "..4294967173"
 */

VALUE
rb_f_sprintf(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_format(argc - 1, argv + 1, GETNTHARG(0));
}

#getcObject

obsolete



# File 'io.c'

/*
 * obsolete
 */

static VALUE
rb_f_getc()
{
    rb_warn("getc is obsolete; use STDIN.getc instead");
    if (TYPE(rb_stdin) != T_FILE) {
    return rb_funcall3(rb_stdin, rb_intern("getc"), 0, 0);
    }
    return rb_io_getc(rb_stdin);
}

#gets(separator = $/) ⇒ 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 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.

Returns:



# File 'io.c'

/*
 *  call-seq:
 *     gets(separator=$/)    => string or nil
 *  
 *  Returns (and assigns to <code>$_</code>) the next line from the list
 *  of files in +ARGV+ (or <code>$*</code>), or from standard
 *  input if no files are present on the command line. Returns
 *  +nil+ at end of file. The optional argument specifies the
 *  record separator. The separator is included with the contents of
 *  each record. A separator of +nil+ reads the entire
 *  contents, and a zero-length separator reads the input one paragraph
 *  at a time, where paragraphs are divided by two consecutive newlines.
 *  If multiple filenames are present in +ARGV+,
 *  +gets(nil)+ will read the contents one file at a time.
 *     
 *     ARGV << "testfile"
 *     print while gets
 *     
 *  <em>produces:</em>
 *     
 *     This is line one
 *     This is line two
 *     This is line three
 *     And so on...
 *     
 *  The style of programming using <code>$_</code> as an implicit
 *  parameter is gradually losing favor in the Ruby community.
 */

static VALUE
rb_f_gets(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE line;

    if (!next_argv()) return Qnil;
    if (TYPE(current_file) != T_FILE) {
    line = rb_funcall3(current_file, rb_intern("gets"), argc, argv);
    }
    else {
    line = argf_getline(argc, argv);
    }
    rb_lastline_set(line);
    return line;
}

#global_variablesArray

Returns an array of the names of global variables.

global_variables.grep /std/   #=> ["$stderr", "$stdout", "$stdin"]

Returns:



# File 'eval.c'

/*
 *  call-seq:
 *     global_variables    => array
 *  
 *  Returns an array of the names of global variables.
 *     
 *     global_variables.grep /std/   #=> ["$stderr", "$stdout", "$stdin"]
 */

VALUE
rb_f_global_variables()
{
    VALUE ary = rb_ary_new();
    char buf[4];
    const char *s = "&`'+123456789";

    st_foreach(rb_global_tbl, gvar_i, ary);
    if (!NIL_P(rb_backref_get())) {
	while (*s) {
	    sprintf(buf, "$%c", *s++);
	    rb_ary_push(ary, rb_str_new2(buf));
	}
    }
    return ary;
}

#gsub(pattern, replacement) ⇒ String #gsub(pattern) {|...| ... } ⇒ String

Equivalent to $_.gsub..., except that $_ receives the modified result.

$_ = "quick brown fox"
gsub /[aeiou]/, '*'   #=> "q**ck br*wn f*x"
$_                    #=> "q**ck br*wn f*x"

Overloads:

  • #gsub(pattern, replacement) ⇒ String

    Returns:

  • #gsub(pattern) {|...| ... } ⇒ String

    Yields:

    • (...)

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     gsub(pattern, replacement)    => string
 *     gsub(pattern) {|...| block }  => string
 *  
 *  Equivalent to <code>$_.gsub...</code>, except that <code>$_</code>
 *  receives the modified result.
 *     
 *     $_ = "quick brown fox"
 *     gsub /[aeiou]/, '*'   #=> "q**ck br*wn f*x"
 *     $_                    #=> "q**ck br*wn f*x"
 */

static VALUE
rb_f_gsub(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str = rb_str_dup(uscore_get());

    if (NIL_P(rb_str_gsub_bang(argc, argv, str)))
    return str;
    rb_lastline_set(str);
    return str;
}

#gsub!(pattern, replacement) ⇒ String? #gsub!(pattern) {|...| ... } ⇒ String?

Equivalent to Kernel::gsub, except nil is returned if $_ is not modified.

$_ = "quick brown fox"
gsub! /cat/, '*'   #=> nil
$_                 #=> "quick brown fox"

Overloads:

  • #gsub!(pattern, replacement) ⇒ String?

    Returns:

  • #gsub!(pattern) {|...| ... } ⇒ String?

    Yields:

    • (...)

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     gsub!(pattern, replacement)    => string or nil
 *     gsub!(pattern) {|...| block }  => string or nil
 *  
 *  Equivalent to <code>Kernel::gsub</code>, except <code>nil</code> is
 *  returned if <code>$_</code> is not modified.
 *     
 *     $_ = "quick brown fox"
 *     gsub! /cat/, '*'   #=> nil
 *     $_                 #=> "quick brown fox"
 */

static VALUE
rb_f_gsub_bang(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_gsub_bang(argc, argv, uscore_get());
}

#Integer(arg) ⇒ Integer

Converts arg to a Fixnum or Bignum. Numeric types are converted directly (with floating point numbers being truncated). If arg is a String, leading radix indicators (0, 0b, and 0x) are honored. Others are converted using to_int and to_i. This behavior is different from that of String#to_i.

Integer(123.999)    #=> 123
Integer("0x1a")     #=> 26
Integer(Time.new)   #=> 1049896590

Returns:



# File 'object.c'

/*
 *  call-seq:
 *     Integer(arg)    => integer
 *  
 *  Converts <i>arg</i> to a <code>Fixnum</code> or <code>Bignum</code>.
 *  Numeric types are converted directly (with floating point numbers
 *  being truncated). If <i>arg</i> is a <code>String</code>, leading
 *  radix indicators (<code>0</code>, <code>0b</code>, and
 *  <code>0x</code>) are honored. Others are converted using
 *  <code>to_int</code> and <code>to_i</code>. This behavior is
 *  different from that of <code>String#to_i</code>.
 *     
 *     Integer(123.999)    #=> 123
 *     Integer("0x1a")     #=> 26
 *     Integer(Time.new)   #=> 1049896590
 */

static VALUE
rb_f_integer(obj, arg)
    VALUE obj, arg;
{
    return rb_Integer(arg);
}

#block_given?Boolean #iterator?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"

Overloads:

  • #block_given?Boolean

    Returns:

    • (Boolean)
  • #iterator?Boolean

    Returns:

    • (Boolean)


# File 'eval.c'

/*
 *  call-seq:
 *     block_given?   => true or false
 *     iterator?      => true or false
 *  
 *  Returns <code>true</code> if <code>yield</code> would execute a
 *  block in the current context. The <code>iterator?</code> 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"
 */


static VALUE
rb_f_block_given_p()
{
    if (ruby_frame->prev && ruby_frame->prev->iter == ITER_CUR && ruby_block)
    return Qtrue;
    return Qfalse;
}

#proc {|...| ... } ⇒ Proc #lambda {|...| ... } ⇒ Proc

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

Overloads:

  • #proc {|...| ... } ⇒ Proc

    Yields:

    • (...)

    Returns:

  • #lambda {|...| ... } ⇒ Proc

    Yields:

    • (...)

    Returns:



# File 'eval.c'

/*
 * call-seq:
 *   proc   { |...| block }  => a_proc
 *   lambda { |...| block }  => a_proc
 *
 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
 * check the number of parameters passed when called.
 */

static VALUE
proc_lambda()
{
    return proc_alloc(rb_cProc, Qtrue);
}

#load(filename, wrap = false) ⇒ true

Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program's global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

Returns:

  • (true)


# File 'eval.c'

/*
 *  call-seq:
 *     load(filename, wrap=false)   => true
 *  
 *  Loads and executes the Ruby
 *  program in the file _filename_. If the filename does not
 *  resolve to an absolute path, the file is searched for in the library
 *  directories listed in <code>$:</code>. 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.
 */


static VALUE
rb_f_load(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, wrap;

    rb_scan_args(argc, argv, "11", &fname, &wrap);
    rb_load(fname, RTEST(wrap));
    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:



# File 'eval.c'

/*
 *  call-seq:
 *     local_variables    => array
 *  
 *  Returns the names of the current local variables.
 *     
 *     fred = 1
 *     for i in 1..10
 *        # ...
 *     end
 *     local_variables   #=> ["fred", "i"]
 */

static VALUE
rb_f_local_variables()
{
    ID *tbl;
    int n, i;
    VALUE ary = rb_ary_new();
    struct RVarmap *vars;

    tbl = ruby_scope->local_tbl;
    if (tbl) {
    n = *tbl++;
    for (i=2; i<n; i++) {  /* skip first 2 ($_ and $~) */
        if (!rb_is_local_id(tbl[i])) continue; /* skip flip states */
        rb_ary_push(ary, rb_str_new2(rb_id2name(tbl[i])));
    }
    }

    vars = ruby_dyna_vars;
    while (vars) {
    if (vars->id && rb_is_local_id(vars->id)) { /* skip $_, $~ and flip states */
        rb_ary_push(ary, rb_str_new2(rb_id2name(vars->id)));
    }
    vars = vars->next;
    }

    return ary;
}

#loop { ... } ⇒ Object

Repeatedly executes the block.

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

StopIteration raised in the block breaks the loop.

Yields:



# File 'eval.c'

/*
 *  call-seq:
 *     loop {|| block } 
 *  
 *  Repeatedly executes the block.
 *     
 *     loop do
 *       print "Input: "
 *       line = gets
 *       break if !line or line =~ /^qQ/
 *       # ...
 *     end
 *
 *  StopIteration raised in the block breaks the loop.
 */

static VALUE
rb_f_loop()
{
    rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0);
    return Qnil;        /* dummy */
}

#open(path[, mode [, perm]]) ⇒ IO? #open(path[, mode [, perm]]) {|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"). (See the table of valid modes on page 331.) If a file is being created, its initial permissions may be set using the integer third parameter.

If a block is specified, it will be invoked with the File object as a parameter, and the file 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 "|" is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not "-", the subprocess runs the command. If a block is associated with an open("|-") call, that block will be 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.

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 I/O object:

open("|-") do |f|
  if f == nil
    puts "in Child"
  else
    puts "Got: #{f.gets}"
  end
end

produces:

Got: in Child

Overloads:

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

    Returns:

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

    Yields:

    • (io)

    Returns:



# File 'io.c'

/*
 *  call-seq:
 *     open(path [, mode [, perm]] )                => io or nil
 *     open(path [, mode [, perm]] ) {|io| block }  => obj
 *  
 *  Creates an <code>IO</code> object connected to the given stream,
 *  file, or subprocess.
 *     
 *  If <i>path</i> does not start with a pipe character
 *  (``<code>|</code>''), treat it as the name of a file to open using
 *  the specified mode (defaulting to ``<code>r</code>''). (See the table
 *  of valid modes on page 331.) If a file is being created, its initial
 *  permissions may be set using the integer third parameter.
 *     
 *  If a block is specified, it will be invoked with the
 *  <code>File</code> object as a parameter, and the file will be
 *  automatically closed when the block terminates. The call
 *  returns the value of the block.
 *     
 *  If <i>path</i> starts with a pipe character, a subprocess is
 *  created, connected to the caller by a pair of pipes. The returned
 *  <code>IO</code> object may be used to write to the standard input
 *  and read from the standard output of this subprocess. If the command
 *  following the ``<code>|</code>'' is a single minus sign, Ruby forks,
 *  and this subprocess is connected to the parent. In the subprocess,
 *  the <code>open</code> call returns <code>nil</code>. If the command
 *  is not ``<code>-</code>'', the subprocess runs the command. If a
 *  block is associated with an <code>open("|-")</code> call, that block
 *  will be run twice---once in the parent and once in the child. The
 *  block parameter will be an <code>IO</code> object in the parent and
 *  <code>nil</code> in the child. The parent's <code>IO</code> object
 *  will be connected to the child's <code>$stdin</code> and
 *  <code>$stdout</code>. The subprocess will be terminated at the end
 *  of the block.
 *     
 *     open("testfile") do |f|
 *       print f.gets
 *     end
 *     
 *  <em>produces:</em>
 *     
 *     This is line one
 *     
 *  Open a subprocess and read its output:
 *     
 *     cmd = open("|date")
 *     print cmd.gets
 *     cmd.close
 *     
 *  <em>produces:</em>
 *     
 *     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
 *     
 *  <em>produces:</em>
 *     
 *     Got: in Child
 *     
 *  Open a subprocess using a block to receive the I/O object:
 *     
 *     open("|-") do |f|
 *       if f == nil
 *         puts "in Child"
 *       else
 *         puts "Got: #{f.gets}"
 *       end
 *     end
 *     
 *  <em>produces:</em>
 *     
 *     Got: in Child
 */

static VALUE
rb_f_open(argc, argv)
    int argc;
    VALUE *argv;
{
    if (argc >= 1) {
    char *str = StringValuePtr(argv[0]);

    if (str[0] == '|') {
        VALUE tmp = rb_str_new(str+1, RSTRING(argv[0])->len-1);
        OBJ_INFECT(tmp, argv[0]);
        argv[0] = tmp;
        return rb_io_s_popen(argc, argv, rb_cIO);
    }
    }
    return rb_io_s_open(argc, argv, rb_cFile);
}

#p(obj, ...) ⇒ nil

For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.

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

produces:

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

Returns:

  • (nil)


# File 'io.c'

/*
 *  call-seq:
 *     p(obj, ...)    => nil
 *  
 *  For each object, directly writes
 *  _obj_.+inspect+ followed by the current output
 *  record separator to the program's standard output.
 *     
 *     S = Struct.new(:name, :state)
 *     s = S['dave', 'TX']
 *     p s
 *     
 *  <em>produces:</em>
 *     
 *     #<S name="dave", state="TX">
 */

static VALUE
rb_f_p(argc, argv)
    int argc;
    VALUE *argv;
{
    int i;

    for (i=0; i<argc; i++) {
    rb_p(argv[i]);
    }
    if (TYPE(rb_stdout) == T_FILE) {
    rb_io_flush(rb_stdout);
    }
    return Qnil;
}

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)


# File 'io.c'

/*
 *  call-seq:
 *     print(obj, ...)    => nil
 *  
 *  Prints each object in turn to <code>$stdout</code>. If the output
 *  field separator (<code>$,</code>) is not +nil+, its
 *  contents will appear between each field. If the output record
 *  separator (<code>$\\</code>) is not +nil+, it will be
 *  appended to the output. If no arguments are given, prints
 *  <code>$_</code>. Objects that aren't strings will be converted by
 *  calling their <code>to_s</code> method.
 *     
 *     print "cat", [1,2,3], 99, "\n"
 *     $, = ", "
 *     $\ = "\n"
 *     print "cat", [1,2,3], 99
 *     
 *  <em>produces:</em>
 *     
 *     cat12399
 *     cat, 1, 2, 3, 99
 */

static VALUE
rb_f_print(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_io_print(argc, argv, rb_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)


# File 'io.c'

/*
 *  call-seq:
 *     printf(io, string [, obj ... ] )    => nil
 *     printf(string [, obj ... ] )        => nil
 *  
 *  Equivalent to:
 *     io.write(sprintf(string, obj, ...)
 *  or
 *     $stdout.write(sprintf(string, obj, ...)
 */

static VALUE
rb_f_printf(argc, argv)
    int argc;
    VALUE argv[];
{
    VALUE out;

    if (argc == 0) return Qnil;
    if (TYPE(argv[0]) == T_STRING) {
    out = rb_stdout;
    }
    else {
    out = argv[0];
    argv++;
    argc--;
    }
    rb_io_write(out, rb_f_sprintf(argc, argv));

    return Qnil;
}

#proc {|...| ... } ⇒ Proc #lambda {|...| ... } ⇒ Proc

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

Overloads:

  • #proc {|...| ... } ⇒ Proc

    Yields:

    • (...)

    Returns:

  • #lambda {|...| ... } ⇒ Proc

    Yields:

    • (...)

    Returns:



# File 'eval.c'

/*
 * call-seq:
 *   proc   { |...| block }  => a_proc
 *   lambda { |...| block }  => a_proc
 *
 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
 * check the number of parameters passed when called.
 */

static VALUE
proc_lambda()
{
    return proc_alloc(rb_cProc, Qtrue);
}

#putc(int) ⇒ Integer

Equivalent to:

$stdout.putc(int)

Returns:



# File 'io.c'

/*
 *  call-seq:
 *     putc(int)   => int
 *  
 *  Equivalent to:
 *
 *    $stdout.putc(int)
 */

static VALUE
rb_f_putc(recv, ch)
    VALUE recv, ch;
{
    return rb_io_putc(rb_stdout, ch);
}

#puts(obj, ...) ⇒ nil

Equivalent to

$stdout.puts(obj, ...)

Returns:

  • (nil)


# File 'io.c'

/*
 *  call-seq:
 *     puts(obj, ...)    => nil
 *  
 *  Equivalent to 
 *
 *      $stdout.puts(obj, ...)
 */

static VALUE
rb_f_puts(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_io_puts(argc, argv, rb_stdout);
    return Qnil;
}

#raiseObject #raise(string) ⇒ Object #raise(exception[, string [, array]]) ⇒ Object #failObject #fail(string) ⇒ Object #fail(exception[, string [, array]]) ⇒ 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 the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller


# File 'eval.c'

/*
 *  call-seq:
 *     raise
 *     raise(string)
 *     raise(exception [, string [, array]])
 *     fail
 *     fail(string)
 *     fail(exception [, string [, array]])
 *  
 *  With no arguments, raises the exception in <code>$!</code> or raises
 *  a <code>RuntimeError</code> if <code>$!</code> is +nil+.
 *  With a single +String+ argument, raises a
 *  +RuntimeError+ with the string as a message. Otherwise,
 *  the first parameter should be the name of an +Exception+
 *  class (or an object that returns an +Exception+ object when sent
 *  an +exception+ message). The optional second parameter sets the
 *  message associated with the exception, and the third parameter is an
 *  array of callback information. Exceptions are caught by the
 *  +rescue+ clause of <code>begin...end</code> blocks.
 *     
 *     raise "Failed to create socket"
 *     raise ArgumentError, "No parameters", caller
 */

static VALUE
rb_f_raise(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_raise_jump(rb_make_exception(argc, argv));
    return Qnil;        /* not reached */
}

#rand(max = 0) ⇒ Numeric

Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.

srand 1234                 #=> 0
[ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
[ rand(10), rand(1000) ]   #=> [6, 817]
srand 1234                 #=> 1234
[ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]

Returns:



# File 'random.c'

/*
 *  call-seq:
 *     rand(max=0)    => number
 *  
 *  Converts <i>max</i> to an integer using max1 =
 *  max<code>.to_i.abs</code>. If the result is zero, returns a
 *  pseudorandom floating point number greater than or equal to 0.0 and
 *  less than 1.0. Otherwise, returns a pseudorandom integer greater
 *  than or equal to zero and less than max1. <code>Kernel::srand</code>
 *  may be used to ensure repeatable sequences of random numbers between
 *  different runs of the program. Ruby currently uses a modified
 *  Mersenne Twister with a period of 2**19937-1.
 *     
 *     srand 1234                 #=> 0
 *     [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
 *     [ rand(10), rand(1000) ]   #=> [6, 817]
 *     srand 1234                 #=> 1234
 *     [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
 */

static VALUE
rb_f_rand(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE vmax;
    long val, max;

    rb_scan_args(argc, argv, "01", &vmax);
    switch (TYPE(vmax)) {
      case T_FLOAT:
    if (RFLOAT(vmax)->value <= LONG_MAX && RFLOAT(vmax)->value >= LONG_MIN) {
        max = (long)RFLOAT(vmax)->value;
        break;
    }
        if (RFLOAT(vmax)->value < 0)
            vmax = rb_dbl2big(-RFLOAT(vmax)->value);
        else
            vmax = rb_dbl2big(RFLOAT(vmax)->value);
    /* fall through */
      case T_BIGNUM:
      bignum:
        {
            struct RBignum *limit = (struct RBignum *)vmax;
            if (!limit->sign) {
                limit = (struct RBignum *)rb_big_clone(vmax);
                limit->sign = 1;
            }
            limit = (struct RBignum *)rb_big_minus((VALUE)limit, INT2FIX(1));
            if (FIXNUM_P((VALUE)limit)) {
                if (FIX2LONG((VALUE)limit) == -1)
                    return rb_float_new(rb_genrand_real());
                return LONG2NUM(limited_rand(FIX2LONG((VALUE)limit)));
            }
            return limited_big_rand(limit);
    }
      case T_NIL:
    max = 0;
    break;
      default:
    vmax = rb_Integer(vmax);
    if (TYPE(vmax) == T_BIGNUM) goto bignum;
    /* fall through */
      case T_FIXNUM:
    max = FIX2LONG(vmax);
    break;
    }

    if (max == 0) {
    return rb_float_new(rb_genrand_real());
    }
    if (max < 0) max = -max;
    val = limited_rand(max-1);
    return LONG2NUM(val);
}

#readline(separator = $/) ⇒ String

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

Returns:



# File 'io.c'

/*
 *  call-seq:
 *     readline(separator=$/)   => string
 *  
 *  Equivalent to <code>Kernel::gets</code>, except
 *  +readline+ raises +EOFError+ at end of file.
 */

static VALUE
rb_f_readline(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE line;

    if (!next_argv()) rb_eof_error();
    ARGF_FORWARD(argc, argv);
    line = rb_f_gets(argc, argv);
    if (NIL_P(line)) {
    rb_eof_error();
    }

    return line;
}

#readlines(separator = $/) ⇒ Array

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

Returns:



# File 'io.c'

/*
 *  call-seq:
 *     readlines(separator=$/)    => array
 *  
 *  Returns an array containing the lines returned by calling
 *  <code>Kernel.gets(<i>separator</i>)</code> until the end of file.
 */

static VALUE
rb_f_readlines(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE line, ary;

    NEXT_ARGF_FORWARD(argc, argv);
    ary = rb_ary_new();
    while (!NIL_P(line = argf_getline(argc, argv))) {
    rb_ary_push(ary, line);
    }

    return ary;
}

#require(string) ⇒ Boolean

Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ".rb", it is loaded as a source file; if the extension is ".so", ".o", or ".dll", or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on to the name. The name of the loaded feature is added to the array in $". A feature will not be loaded if it's name already appears in $". However, the file name is not converted to an absolute path, so that "require 'a';require './a'" will load a.rb twice.

require "my-library.rb"
require "db-driver"

Returns:

  • (Boolean)


# File 'eval.c'

/*
 *  call-seq:
 *     require(string)    => true or false
 *  
 *  Ruby tries to load the library named _string_, returning
 *  +true+ if successful. If the filename does not resolve to
 *  an absolute path, it will be searched for in the directories listed
 *  in <code>$:</code>. If the file has the extension ``.rb'', it is
 *  loaded as a source file; if the extension is ``.so'', ``.o'', or
 *  ``.dll'', or whatever the default shared library extension is on
 *  the current platform, Ruby loads the shared library as a Ruby
 *  extension. Otherwise, Ruby tries adding ``.rb'', ``.so'', and so on
 *  to the name. The name of the loaded feature is added to the array in
 *  <code>$"</code>. A feature will not be loaded if it's name already
 *  appears in <code>$"</code>. However, the file name is not converted
 *  to an absolute path, so that ``<code>require 'a';require
 *  './a'</code>'' will load <code>a.rb</code> twice.
 *     
 *     require "my-library.rb"
 *     require "db-driver"
 */

VALUE
rb_f_require(obj, fname)
    VALUE obj, fname;
{
    return rb_require_safe(fname, ruby_safe_level);
}

#scan(pattern) ⇒ Array #scan(pattern) {|///| ... } ⇒ Object

Equivalent to calling $_.scan. See String#scan.

Overloads:

  • #scan(pattern) ⇒ Array

    Returns:

  • #scan(pattern) {|///| ... } ⇒ Object

    Yields:

    • (///)


# File 'string.c'

/*
 *  call-seq:
 *     scan(pattern)                   => array
 *     scan(pattern) {|///| block }    => $_
 *  
 *  Equivalent to calling <code>$_.scan</code>. See
 *  <code>String#scan</code>.
 */

static VALUE
rb_f_scan(self, pat)
    VALUE self, pat;
{
    return rb_str_scan(uscore_get(), pat);
}

#select(read_array) ⇒ Object

[, error_array

[, timeout]]] ) =>  array  or  nil

See Kernel#select.



# File 'io.c'

/*
 *  call-seq:
 *     IO.select(read_array 
 *               [, write_array 
 *               [, error_array 
 *               [, timeout]]] ) =>  array  or  nil
 *  
 *  See <code>Kernel#select</code>.
 */

static VALUE
rb_f_select(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE read, write, except, timeout, res, list;
    fd_set rset, wset, eset, pset;
    fd_set *rp, *wp, *ep;
    struct timeval *tp, timerec;
    rb_io_t *fptr;
    long i;
    int max = 0, n;
    int interrupt_flag = 0;
    int pending = 0;

    rb_scan_args(argc, argv, "13", &read, &write, &except, &timeout);
    if (NIL_P(timeout)) {
    tp = 0;
    }
    else {
    timerec = rb_time_interval(timeout);
    tp = &timerec;
    }

    FD_ZERO(&pset);
    if (!NIL_P(read)) {
    Check_Type(read, T_ARRAY);
    rp = &rset;
    FD_ZERO(rp);
    for (i=0; i<RARRAY(read)->len; i++) {
        GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
        FD_SET(fileno(fptr->f), rp);
        if (READ_DATA_PENDING(fptr->f)) { /* check for buffered data */
        pending++;
        FD_SET(fileno(fptr->f), &pset);
        }
        if (max < fileno(fptr->f)) max = fileno(fptr->f);
    }
    if (pending) {     /* no blocking if there's buffered data */
        timerec.tv_sec = timerec.tv_usec = 0;
        tp = &timerec;
    }
    }
    else
    rp = 0;

    if (!NIL_P(write)) {
    Check_Type(write, T_ARRAY);
    wp = &wset;
    FD_ZERO(wp);
    for (i=0; i<RARRAY(write)->len; i++) {
        GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
        FD_SET(fileno(fptr->f), wp);
        if (max < fileno(fptr->f)) max = fileno(fptr->f);
        if (fptr->f2) {
        FD_SET(fileno(fptr->f2), wp);
        if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
        }
    }
    }
    else
    wp = 0;

    if (!NIL_P(except)) {
    Check_Type(except, T_ARRAY);
    ep = &eset;
    FD_ZERO(ep);
    for (i=0; i<RARRAY(except)->len; i++) {
        GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
        FD_SET(fileno(fptr->f), ep);
        if (max < fileno(fptr->f)) max = fileno(fptr->f);
        if (fptr->f2) {
        FD_SET(fileno(fptr->f2), ep);
        if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
        }
    }
    }
    else {
    ep = 0;
    }

    max++;

    n = rb_thread_select(max, rp, wp, ep, tp);
    if (n < 0) {
    rb_sys_fail(0);
    }
    if (!pending && n == 0) return Qnil; /* returns nil on timeout */

    res = rb_ary_new2(3);
    rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
    rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
    rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));

    if (interrupt_flag == 0) {
    if (rp) {
        list = RARRAY(res)->ptr[0];
        for (i=0; i< RARRAY(read)->len; i++) {
        GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
        if (FD_ISSET(fileno(fptr->f), rp)
            || FD_ISSET(fileno(fptr->f), &pset)) {
            rb_ary_push(list, rb_ary_entry(read, i));
        }
        }
    }

    if (wp) {
        list = RARRAY(res)->ptr[1];
        for (i=0; i< RARRAY(write)->len; i++) {
        GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
        if (FD_ISSET(fileno(fptr->f), wp)) {
            rb_ary_push(list, rb_ary_entry(write, i));
        }
        else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), wp)) {
            rb_ary_push(list, rb_ary_entry(write, i));
        }
        }
    }

    if (ep) {
        list = RARRAY(res)->ptr[2];
        for (i=0; i< RARRAY(except)->len; i++) {
        GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
        if (FD_ISSET(fileno(fptr->f), ep)) {
            rb_ary_push(list, rb_ary_entry(except, i));
        }
        else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), ep)) {
            rb_ary_push(list, rb_ary_entry(except, i));
        }
        }
    }
    }

    return res;         /* returns an empty array on interrupt */
}

#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. proc takes up to six parameters: an event name, a filename, a line number, an object id, a binding, and the name of a class. proc is invoked whenever an event occurs. Events are: c-call (call a C-language routine), c-return (return from a C-language routine), call (call a Ruby method), class (start a class or module definition), end (finish a class or module definition), line (execute code on a new line), raise (raise an exception), and return (return from a Ruby method). Tracing is disabled within the context of proc.

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)


# File 'eval.c'

/*
 *  call-seq:
 *     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+. _proc_ takes up
 *  to six parameters: an event name, a filename, a line number, an
 *  object id, a binding, and the name of a class. _proc_ is
 *  invoked whenever an event occurs. Events are: <code>c-call</code>
 *  (call a C-language routine), <code>c-return</code> (return from a
 *  C-language routine), <code>call</code> (call a Ruby method),
 *  <code>class</code> (start a class or module definition),
 *  <code>end</code> (finish a class or module definition),
 *  <code>line</code> (execute code on a new line), <code>raise</code>
 *  (raise an exception), and <code>return</code> (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
 */


static VALUE
set_trace_func(obj, trace)
    VALUE obj, trace;
{
    rb_event_hook_t *hook;

    rb_secure(4);
    if (NIL_P(trace)) {
    trace_func = 0;
    rb_remove_event_hook(call_trace_func);
    return Qnil;
    }
    if (!rb_obj_is_proc(trace)) {
    rb_raise(rb_eTypeError, "trace_func needs to be Proc");
    }
    trace_func = trace;
    for (hook = event_hooks; hook; hook = hook->next) {
    if (hook->func == call_trace_func)
        return trace;
    }
    rb_add_event_hook(call_trace_func, RUBY_EVENT_ALL);
    return trace;
}

#sleep([duration]) ⇒ Fixnum

Suspends the current thread for duration seconds (which may be any number, including a Float with fractional seconds). Returns the actual number of seconds slept (rounded), which may be less than that asked for if another thread calls Thread#run. Zero arguments causes sleep to sleep forever.

Time.new    #=> Wed Apr 09 08:56:32 CDT 2003
sleep 1.2   #=> 1
Time.new    #=> Wed Apr 09 08:56:33 CDT 2003
sleep 1.9   #=> 2
Time.new    #=> Wed Apr 09 08:56:35 CDT 2003

Returns:



# File 'process.c'

/*
 *  call-seq:
 *     sleep([duration])    => fixnum
 *
 *  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 <code>Thread#run</code>. Zero arguments causes +sleep+ to sleep
 *  forever.
 *
 *     Time.new    #=> Wed Apr 09 08:56:32 CDT 2003
 *     sleep 1.2   #=> 1
 *     Time.new    #=> Wed Apr 09 08:56:33 CDT 2003
 *     sleep 1.9   #=> 2
 *     Time.new    #=> Wed Apr 09 08:56:35 CDT 2003
 */

static VALUE
rb_f_sleep(argc, argv)
    int argc;
    VALUE *argv;
{
    int beg, end;

    beg = time(0);
    if (argc == 0) {
    rb_thread_sleep_forever();
    }
    else if (argc == 1) {
    rb_thread_wait_for(rb_time_interval(argv[0]));
    }
    else {
    rb_raise(rb_eArgError, "wrong number of arguments");
    }

    end = time(0) - beg;

    return INT2FIX(end);
}

#split([pattern [, limit]]) ⇒ Array

Equivalent to $_.split(pattern, limit). See String#split.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     split([pattern [, limit]])    => array
 *  
 *  Equivalent to <code>$_.split(<i>pattern</i>, <i>limit</i>)</code>.
 *  See <code>String#split</code>.
 */

static VALUE
rb_f_split(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_split_m(argc, argv, uscore_get());
}

#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. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

Flag     | Applies to   | Meaning
---------+--------------+-----------------------------------------
space    | bdeEfgGiouxX | Leave a space at the start of
         |              | positive numbers.
---------+--------------+-----------------------------------------
(digit)$ | all          | Specifies the absolute argument number
         |              | for this field. Absolute and relative
         |              | argument numbers cannot be mixed in a
         |              | sprintf string.
---------+--------------+-----------------------------------------
 #       | beEfgGoxX    | Use an alternative format. For the
         |              | conversions `o', `x', `X', and `b',
         |              | prefix the result with ``0'', ``0x'', ``0X'',
         |              |  and ``0b'', respectively. For `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.
---------+--------------+-----------------------------------------
+        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
---------+--------------+-----------------------------------------
-        | all          | Left-justify the result of this conversion.
---------+--------------+-----------------------------------------
0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
---------+--------------+-----------------------------------------
*        | 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.

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

The field types are:

Field |  Conversion
------+--------------------------------------------------------------
  b   | Convert argument as a binary number.
  c   | Argument is the numeric code for a single character.
  d   | Convert argument as a decimal number.
  E   | Equivalent to `e', but uses an uppercase E to indicate
      | the exponent.
  e   | Convert floating point argument into exponential notation
      | with one digit before the decimal point. The precision
      | determines the number of fractional digits (defaulting to six).
  f   | Convert floating point argument as [-]ddd.ddd,
      |  where the precision determines the number of digits after
      | the decimal point.
  G   | Equivalent to `g', but use an uppercase `E' in exponent form.
  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 d.dddd form otherwise.
  i   | Identical to `d'.
  o   | Convert argument as an octal number.
  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.
  u   | Treat argument as an unsigned decimal number. Negative integers
      | are displayed as a 32 bit two's complement plus one for the
      | underlying architecture; that is, 2 ** 32 + n.  However, since
      | Ruby has no inherent limit on bits used to represent the
      | integer, this value is preceded by two dots (..) in order to
      | indicate a infinite number of leading sign bits.
  X   | Convert argument as a hexadecimal number using uppercase
      | letters. Negative numbers will be displayed with two
      | leading periods (representing an infinite string of
      | leading 'FF's.
  x   | Convert argument as a hexadecimal number.
      | Negative numbers will be displayed with two
      | leading periods (representing an infinite string of
      | leading 'ff's.

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)                        #=> "..4294967173"

Overloads:

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

    Returns:

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

    Returns:



# File 'object.c'

/*
 *  call-seq:
 *     format(format_string [, arguments...] )   => string
 *     sprintf(format_string [, arguments...] )  => string
 *  
 *  Returns the string resulting from applying <i>format_string</i> to
 *  any additional arguments. Within the format string, any characters
 *  other than format sequences are copied to the result. A format
 *  sequence consists of a percent sign, followed by optional flags,
 *  width, and precision indicators, then terminated with a field type
 *  character. The field type controls how the corresponding
 *  <code>sprintf</code> argument is to be interpreted, while the flags
 *  modify that interpretation. The field type characters are listed
 *  in the table at the end of this section. The flag characters are:
 *
 *    Flag     | Applies to   | Meaning
 *    ---------+--------------+-----------------------------------------
 *    space    | bdeEfgGiouxX | Leave a space at the start of 
 *             |              | positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    (digit)$ | all          | Specifies the absolute argument number
 *             |              | for this field. Absolute and relative
 *             |              | argument numbers cannot be mixed in a
 *             |              | sprintf string.
 *    ---------+--------------+-----------------------------------------
 *     #       | beEfgGoxX    | Use an alternative format. For the
 *             |              | conversions `o', `x', `X', and `b', 
 *             |              | prefix the result with ``0'', ``0x'', ``0X'',
 *             |              |  and ``0b'', respectively. For `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.
 *    ---------+--------------+-----------------------------------------
 *    +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    -        | all          | Left-justify the result of this conversion.
 *    ---------+--------------+-----------------------------------------
 *    0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
 *    ---------+--------------+-----------------------------------------
 *    *        | 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.
 *
 *     
 *  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. 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 <code>%10.10s</code> will always contribute exactly ten
 *  characters to the result.)
 *
 *  The field types are:
 *
 *      Field |  Conversion
 *      ------+--------------------------------------------------------------
 *        b   | Convert argument as a binary number.
 *        c   | Argument is the numeric code for a single character.
 *        d   | Convert argument as a decimal number.
 *        E   | Equivalent to `e', but uses an uppercase E to indicate
 *            | the exponent.
 *        e   | Convert floating point argument into exponential notation 
 *            | with one digit before the decimal point. The precision
 *            | determines the number of fractional digits (defaulting to six).
 *        f   | Convert floating point argument as [-]ddd.ddd, 
 *            |  where the precision determines the number of digits after
 *            | the decimal point.
 *        G   | Equivalent to `g', but use an uppercase `E' in exponent form.
 *        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 d.dddd form otherwise.
 *        i   | Identical to `d'.
 *        o   | Convert argument as an octal number.
 *        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.
 *        u   | Treat argument as an unsigned decimal number. Negative integers
 *            | are displayed as a 32 bit two's complement plus one for the
 *            | underlying architecture; that is, 2 ** 32 + n.  However, since
 *            | Ruby has no inherent limit on bits used to represent the
 *            | integer, this value is preceded by two dots (..) in order to
 *            | indicate a infinite number of leading sign bits.
 *        X   | Convert argument as a hexadecimal number using uppercase
 *            | letters. Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'FF's.
 *        x   | Convert argument as a hexadecimal number.
 *            | Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'ff's.
 *     
 *  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)                        #=> "..4294967173"
 */

VALUE
rb_f_sprintf(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_format(argc - 1, argv + 1, GETNTHARG(0));
}

#srand(number = 0) ⇒ Object

Seeds the pseudorandom number generator to the value of number.to_i.abs. If number is omitted, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.



# File 'random.c'

/*
 *  call-seq:
 *     srand(number=0)    => old_seed
 *  
 *  Seeds the pseudorandom number generator to the value of
 *  <i>number</i>.<code>to_i.abs</code>. If <i>number</i> is omitted,
 *  seeds the generator using a combination of the time, the
 *  process id, and a sequence number. (This is also the behavior if
 *  <code>Kernel::rand</code> is called without previously calling
 *  <code>srand</code>, but without the sequence.) By setting the seed
 *  to a known value, scripts can be made deterministic during testing.
 *  The previous seed value is returned. Also see <code>Kernel::rand</code>.
 */

static VALUE
rb_f_srand(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE seed, old;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &seed) == 0) {
    seed = random_seed();
    }
    old = rand_init(seed);

    return old;
}

#String(arg) ⇒ String

Converts arg to a String by calling its to_s method.

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

Returns:



# File 'object.c'

/*
 *  call-seq:
 *     String(arg)   => string
 *  
 *  Converts <i>arg</i> to a <code>String</code> by calling its
 *  <code>to_s</code> method.
 *     
 *     String(self)        #=> "main"
 *     String(self.class   #=> "Object"
 *     String(123456)      #=> "123456"
 */

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

#sub(pattern, replacement) ⇒ Object #sub(pattern) { ... } ⇒ Object

Equivalent to $_.sub(args), except that $_ will be updated if substitution occurs.

Overloads:

  • #sub(pattern) { ... } ⇒ Object

    Yields:



# File 'string.c'

/*
 *  call-seq:
 *     sub(pattern, replacement)   => $_
 *     sub(pattern) { block }      => $_
 *  
 *  Equivalent to <code>$_.sub(<i>args</i>)</code>, except that
 *  <code>$_</code> will be updated if substitution occurs.
 */

static VALUE
rb_f_sub(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str = rb_str_dup(uscore_get());

    if (NIL_P(rb_str_sub_bang(argc, argv, str)))
    return str;
    rb_lastline_set(str);
    return str;
}

#sub!(pattern, replacement) ⇒ nil #sub!(pattern) {|...| ... } ⇒ nil

Equivalent to $_.sub!(args).

Overloads:

  • #sub!(pattern, replacement) ⇒ nil

    Returns:

    • (nil)
  • #sub!(pattern) {|...| ... } ⇒ nil

    Yields:

    • (...)

    Returns:

    • (nil)


# File 'string.c'

/*
 *  call-seq:
 *     sub!(pattern, replacement)    => $_ or nil
 *     sub!(pattern) {|...| block }  => $_ or nil
 *  
 *  Equivalent to <code>$_.sub!(<i>args</i>)</code>.
 */

static VALUE
rb_f_sub_bang(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_sub_bang(argc, argv, uscore_get());
}

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

Calls the operating system function identified by fixnum, passing in the arguments, which must be either String objects, or Integer objects that ultimately fit within a native long. Up to nine parameters may be passed (14 on the Atari-ST). The function identified by fixnum is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h.

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

produces:

hello

Returns:



# File 'io.c'

/*
 *  call-seq:
 *     syscall(fixnum [, args...])   => integer
 *  
 *  Calls the operating system function identified by _fixnum_,
 *  passing in the arguments, which must be either +String+
 *  objects, or +Integer+ objects that ultimately fit within
 *  a native +long+. Up to nine parameters may be passed (14
 *  on the Atari-ST). The function identified by _fixnum_ is system
 *  dependent. On some Unix systems, the numbers may be obtained from a
 *  header file called <code>syscall.h</code>.
 *     
 *     syscall 4, 1, "hello\n", 6   # '4' is write(2) on our box
 *     
 *  <em>produces:</em>
 *     
 *     hello
 */

static VALUE
rb_f_syscall(argc, argv)
    int argc;
    VALUE *argv;
{
#if defined(HAVE_SYSCALL) && !defined(__CHECKER__)
#ifdef atarist
    unsigned long arg[14]; /* yes, we really need that many ! */
#else
    unsigned long arg[8];
#endif
    int retval = -1;
    int i = 1;
    int items = argc - 1;

    /* This probably won't work on machines where sizeof(long) != sizeof(int)
     * or where sizeof(long) != sizeof(char*).  But such machines will
     * not likely have syscall implemented either, so who cares?
     */

    rb_secure(2);
    if (argc == 0)
    rb_raise(rb_eArgError, "too few arguments for syscall");
    if (argc > sizeof(arg) / sizeof(arg[0]))
    rb_raise(rb_eArgError, "too many arguments for syscall");
    arg[0] = NUM2LONG(argv[0]); argv++;
    while (items--) {
    VALUE v = rb_check_string_type(*argv);

    if (!NIL_P(v)) {
        StringValue(v);
        rb_str_modify(v);
        arg[i] = (unsigned long)StringValueCStr(v);
    }
    else {
        arg[i] = (unsigned long)NUM2LONG(*argv);
    }
    argv++;
    i++;
    }
    TRAP_BEG;
    switch (argc) {
      case 1:
    retval = syscall(arg[0]);
    break;
      case 2:
    retval = syscall(arg[0],arg[1]);
    break;
      case 3:
    retval = syscall(arg[0],arg[1],arg[2]);
    break;
      case 4:
    retval = syscall(arg[0],arg[1],arg[2],arg[3]);
    break;
      case 5:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4]);
    break;
      case 6:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
    break;
      case 7:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
    break;
      case 8:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7]);
    break;
#ifdef atarist
      case 9:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7], arg[8]);
    break;
      case 10:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7], arg[8], arg[9]);
    break;
      case 11:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7], arg[8], arg[9], arg[10]);
    break;
      case 12:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7], arg[8], arg[9], arg[10], arg[11]);
    break;
      case 13:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7], arg[8], arg[9], arg[10], arg[11], arg[12]);
    break;
      case 14:
    retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
      arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13]);
    break;
#endif /* atarist */
    }
    TRAP_END;
    if (retval < 0) rb_sys_fail(0);
    return INT2NUM(retval);
#else
    rb_notimplement();
    return Qnil;        /* not reached */
#endif
}

#system(cmd[, arg, ...]) ⇒ Boolean

Executes cmd in a subshell, returning true if the command was found and ran successfully, false otherwise. An error status is available in $?. The arguments are processed in the same way as for Kernel::exec.

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

produces:

config.h main.rb
*

Returns:

  • (Boolean)


# File 'process.c'

/*
 *  call-seq:
 *     system(cmd [, arg, ...])    => true or false
 *
 *  Executes _cmd_ in a subshell, returning +true+ if
 *  the command was found and ran successfully, +false+
 *  otherwise. An error status is available in <code>$?</code>. The
 *  arguments are processed in the same way as for
 *  <code>Kernel::exec</code>.
 *
 *     system("echo *")
 *     system("echo", "*")
 *
 *  <em>produces:</em>
 *
 *     config.h main.rb
 *     *
 */

static VALUE
rb_f_system(argc, argv)
    int argc;
    VALUE *argv;
{
    int status;
#if defined(__EMX__)
    VALUE cmd;

    fflush(stdout);
    fflush(stderr);
    if (argc == 0) {
    rb_last_status = Qnil;
    rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
    if (RARRAY(argv[0])->len != 2) {
        rb_raise(rb_eArgError, "wrong first argument");
    }
    argv[0] = RARRAY(argv[0])->ptr[0];
    }
    cmd = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));

    SafeStringValue(cmd);
    status = do_spawn(RSTRING(cmd)->ptr);
    last_status_set(status, 0);
#elif defined(__human68k__) || defined(__DJGPP__) || defined(_WIN32)
    volatile VALUE prog = 0;

    fflush(stdout);
    fflush(stderr);
    if (argc == 0) {
    rb_last_status = Qnil;
    rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
    if (RARRAY(argv[0])->len != 2) {
        rb_raise(rb_eArgError, "wrong first argument");
    }
    prog = RARRAY(argv[0])->ptr[0];
    argv[0] = RARRAY(argv[0])->ptr[1];
    }

    if (argc == 1 && prog == 0) {
#if defined(_WIN32)
    SafeStringValue(argv[0]);
    status = do_spawn(P_WAIT, StringValueCStr(argv[0]));
#else
    status = proc_spawn(argv[0]);
#endif
    }
    else {
    status = proc_spawn_n(argc, argv, prog);
    }
#if !defined(_WIN32)
    last_status_set(status == -1 ? 127 : status, 0);
#else
    if (status == -1)
    last_status_set(0x7f << 8, 0);
#endif
#elif defined(__VMS)
    VALUE cmd;

    if (argc == 0) {
    rb_last_status = Qnil;
    rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
    if (RARRAY(argv[0])->len != 2) {
        rb_raise(rb_eArgError, "wrong first argument");
    }
    argv[0] = RARRAY(argv[0])->ptr[0];
    }
    cmd = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));

    SafeStringValue(cmd);
    status = system(StringValueCStr(cmd));
    last_status_set((status & 0xff) << 8, 0);
#else
    volatile VALUE prog = 0;
    int pid;
    struct rb_exec_arg earg;
    RETSIGTYPE (*chfunc)(int);

    fflush(stdout);
    fflush(stderr);
    if (argc == 0) {
    rb_last_status = Qnil;
    rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
    if (RARRAY(argv[0])->len != 2) {
        rb_raise(rb_eArgError, "wrong first argument");
    }
    prog = RARRAY(argv[0])->ptr[0];
    argv[0] = RARRAY(argv[0])->ptr[1];
    }
    proc_prepare_args(&earg, argc, argv, prog);

    chfunc = signal(SIGCHLD, SIG_DFL);
  retry:
    before_exec();
    pid = fork();
    if (pid == 0) {
    /* child process */
    rb_thread_atfork();
    rb_protect(proc_exec_args, (VALUE)&earg, NULL);
    _exit(127);
    }
    after_exec();
    if (pid < 0) {
    if (errno == EAGAIN) {
        rb_thread_sleep(1);
        goto retry;
    }
    }
    else {
    rb_syswait(pid);
    }
    signal(SIGCHLD, chfunc);
    if (pid < 0) rb_sys_fail(0);
    status = NUM2INT(rb_last_status);
#endif

    if (status == EXIT_SUCCESS) return Qtrue;
    return Qfalse;
}

#test(int_cmd, file1[, file2]) ⇒ Object

Uses the integer aCmd to perform various tests on file1 (first table below) or on file1 and file2 (second table).

File tests on a single file:

Test   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:



# File 'file.c'

/*
 *  call-seq:
 *     test(int_cmd, file1 [, file2] ) => obj
 *  
 *  Uses the integer <i>aCmd</i> to perform various tests on
 *  <i>file1</i> (first table below) or on <i>file1</i> and
 *  <i>file2</i> (second table).
 *     
 *  File tests on a single file:
 *
 *    Test   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
 */

static VALUE
rb_f_test(argc, argv)
    int argc;
    VALUE *argv;
{
    int cmd;

    if (argc == 0) rb_raise(rb_eArgError, "wrong number of arguments");
#if 0 /* 1.7 behavior? */
    if (argc == 1) {
    return RTEST(argv[0]) ? Qtrue : Qfalse;
    }
#endif
    cmd = NUM2CHR(argv[0]);
    if (cmd == 0) return Qfalse;
    if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
    CHECK(1);
    switch (cmd) {
      case 'b':
        return test_b(0, argv[1]);

      case 'c':
        return test_c(0, argv[1]);

      case 'd':
        return test_d(0, argv[1]);

      case 'a':
      case 'e':
        return test_e(0, argv[1]);

      case 'f':
        return test_f(0, argv[1]);

      case 'g':
        return test_sgid(0, argv[1]);

      case 'G':
        return test_grpowned(0, argv[1]);

      case 'k':
        return test_sticky(0, argv[1]);

      case 'l':
        return test_l(0, argv[1]);

      case 'o':
        return test_owned(0, argv[1]);

      case 'O':
        return test_rowned(0, argv[1]);

      case 'p':
        return test_p(0, argv[1]);

      case 'r':
        return test_r(0, argv[1]);

      case 'R':
        return test_R(0, argv[1]);

      case 's':
        return test_s(0, argv[1]);

      case 'S':
        return test_S(0, argv[1]);

      case 'u':
        return test_suid(0, argv[1]);

      case 'w':
        return test_w(0, argv[1]);

      case 'W':
        return test_W(0, argv[1]);

      case 'x':
        return test_x(0, argv[1]);

      case 'X':
        return test_X(0, argv[1]);

      case 'z':
        return test_z(0, argv[1]);
    }
    }

    if (strchr("MAC", cmd)) {
    struct stat st;

    CHECK(1);
    if (rb_stat(argv[1], &st) == -1) {
        rb_sys_fail(RSTRING(argv[1])->ptr);
    }

    switch (cmd) {
      case 'A':
        return rb_time_new(st.st_atime, 0);
      case 'M':
        return rb_time_new(st.st_mtime, 0);
      case 'C':
        return rb_time_new(st.st_ctime, 0);
    }
    }

    if (cmd == '-') {
    CHECK(2);
    return test_identical(0, argv[1], argv[2]);
    }

    if (strchr("=<>", cmd)) {
    struct stat st1, st2;

    CHECK(2);
    if (rb_stat(argv[1], &st1) < 0) return Qfalse;
    if (rb_stat(argv[2], &st2) < 0) return Qfalse;

    switch (cmd) {
      case '=':
        if (st1.st_mtime == st2.st_mtime) return Qtrue;
        return Qfalse;

      case '>':
        if (st1.st_mtime > st2.st_mtime) return Qtrue;
        return Qfalse;

      case '<':
        if (st1.st_mtime < st2.st_mtime) return Qtrue;
        return Qfalse;
    }
    }
    /* unknown command */
    rb_raise(rb_eArgError, "unknown command ?%c", cmd);
    return Qnil;        /* not reached */
}

#throw(symbol[, obj]) ⇒ Object

Transfers control to the end of the active catch block waiting for symbol. Raises NameError if there is no catch block for the symbol. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.



# File 'eval.c'

/*
 *  call-seq:
 *     throw(symbol [, obj])
 *  
 *  Transfers control to the end of the active +catch+ block
 *  waiting for _symbol_. Raises +NameError+ if there
 *  is no +catch+ block for the symbol. The optional second
 *  parameter supplies a return value for the +catch+ block,
 *  which otherwise defaults to +nil+. For examples, see
 *  <code>Kernel::catch</code>.
 */

static VALUE
rb_f_throw(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE tag, value;
    struct tag *tt = prot_tag;

    rb_scan_args(argc, argv, "11", &tag, &value);
    tag = ID2SYM(rb_to_id(tag));

    while (tt) {
    if (tt->tag == tag) {
        tt->dst = tag;
        tt->retval = value;
        break;
    }
    if (tt->tag == PROT_THREAD) {
        rb_raise(rb_eThreadError, "uncaught throw `%s' in thread 0x%lx",
             rb_id2name(SYM2ID(tag)),
             curr_thread);
    }
    tt = tt->prev;
    }
    if (!tt) {
    rb_name_error(SYM2ID(tag), "uncaught throw `%s'", rb_id2name(SYM2ID(tag)));
    }
    rb_trap_restore_mask();
    JUMP_TAG(TAG_THROW);
#ifndef __GNUC__
    return Qnil;        /* not reached */
#endif
}

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


# File 'eval.c'

/*
 *  call-seq:
 *     trace_var(symbol, cmd )             => nil
 *     trace_var(symbol) {|val| block }    => 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
 *  <code>Kernel::untrace_var</code>.
 *     
 *     trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
 *     $_ = "hello"
 *     $_ = ' there'
 *     
 *  <em>produces:</em>
 *     
 *     $_ is now 'hello'
 *     $_ is now ' there'
 */

VALUE
rb_f_trace_var(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE var, cmd;
    struct global_entry *entry;
    struct trace_var *trace;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) {
	cmd = rb_block_proc();
    }
    if (NIL_P(cmd)) {
	return rb_f_untrace_var(argc, argv);
    }
    entry = rb_global_entry(rb_to_id(var));
    if (OBJ_TAINTED(cmd)) {
	rb_raise(rb_eSecurityError, "Insecure: tainted variable trace");
    }
    trace = ALLOC(struct trace_var);
    trace->next = entry->var->trace;
    trace->func = rb_trace_eval;
    trace->data = cmd;
    trace->removed = 0;
    entry->var->trace = trace;

    return Qnil;
}

#trap(signal, proc) ⇒ 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 operating system's default handler will be invoked. If the command is "EXIT", the script will be terminated by the signal. Otherwise, the given command or block will be run. The special signal name "EXIT" or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD")  { puts "Child died" }
fork && Process.wait

produces:

Terminating: 27461
Child died
Terminating: 27460

Overloads:



# File 'signal.c'

/*
 * call-seq:
 *   Signal.trap( signal, proc ) => obj
 *   Signal.trap( signal ) {| | block } => obj
 *
 * Specifies the handling of signals. The first parameter is a signal
 * name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a
 * signal number. The characters ``SIG'' may be omitted from the
 * signal name. The command or block specifies code to be run when the
 * signal is raised. If the command is the string ``IGNORE'' or
 * ``SIG_IGN'', the signal will be ignored. If the command is
 * ``DEFAULT'' or ``SIG_DFL'', the operating system's default handler
 * will be invoked. If the command is ``EXIT'', the script will be
 * terminated by the signal. Otherwise, the given command or block
 * will be run.
 * The special signal name ``EXIT'' or signal number zero will be
 * invoked just prior to program termination.
 * trap returns the previous handler for the given signal.
 *
 *     Signal.trap(0, proc { puts "Terminating: #{$$}" })
 *     Signal.trap("CLD")  { puts "Child died" }
 *     fork && Process.wait
 *
 * produces:
 *     Terminating: 27461
 *     Child died
 *     Terminating: 27460
 */
static VALUE
sig_trap(argc, argv)
    int argc;
    VALUE *argv;
{
    struct trap_arg arg;

    rb_secure(2);
    if (argc == 0 || argc > 2) {
    rb_raise(rb_eArgError, "wrong number of arguments -- trap(sig, cmd)/trap(sig){...}");
    }

    arg.sig = argv[0];
    if (argc == 1) {
    arg.cmd = rb_block_proc();
    }
    else if (argc == 2) {
    arg.cmd = argv[1];
    }

    if (OBJ_TAINTED(arg.cmd)) {
    rb_raise(rb_eSecurityError, "Insecure: tainted signal trap");
    }
#if USE_TRAP_MASK
    /* disable interrupt */
# ifdef HAVE_SIGPROCMASK
    sigfillset(&arg.mask);
    sigprocmask(SIG_BLOCK, &arg.mask, &arg.mask);
# else
    arg.mask = sigblock(~0);
# endif

    return rb_ensure(trap, (VALUE)&arg, trap_ensure, (VALUE)&arg);
#else
    return trap(&arg);
#endif
}

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



# File 'eval.c'

/*
 *  call-seq:
 *     untrace_var(symbol [, cmd] )   => array or nil
 *  
 *  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.
 */

VALUE
rb_f_untrace_var(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE var, cmd;
    ID id;
    struct global_entry *entry;
    struct trace_var *trace;
    st_data_t data;

    rb_secure(4);
    rb_scan_args(argc, argv, "11", &var, &cmd);
    id = rb_to_id(var);
    if (!st_lookup(rb_global_tbl, id, &data)) {
	rb_name_error(id, "undefined global variable %s", rb_id2name(id));
    }

    trace = (entry = (struct global_entry *)data)->var->trace;
    if (NIL_P(cmd)) {
	VALUE ary = rb_ary_new();

	while (trace) {
	    struct trace_var *next = trace->next;
	    rb_ary_push(ary, (VALUE)trace->data);
	    trace->removed = 1;
	    trace = next;
	}

	if (!entry->var->block_trace) remove_trace(entry->var);
	return ary;
    }
    else {
	while (trace) {
	    if (trace->data == cmd) {
		trace->removed = 1;
		if (!entry->var->block_trace) remove_trace(entry->var);
		return rb_ary_new3(1, cmd);
	    }
	    trace = trace->next;
	}
    }
    return Qnil;
}

#warn(msg) ⇒ nil

Display the given message (followed by a newline) on STDERR unless warnings are disabled (for example with the -W0 flag).

Returns:

  • (nil)


# File 'error.c'

/*
 * call-seq:
 *    warn(msg)   => nil
 *
 * Display the given message (followed by a newline) on STDERR unless
 * warnings are disabled (for example with the <code>-W0</code> flag).
 */

static VALUE
rb_warn_m(self, mesg)
    VALUE self, mesg;
{
    if (!NIL_P(ruby_verbose)) {
    rb_io_write(rb_stderr, mesg);
    rb_io_write(rb_stderr, rb_default_rs);
    }
    return Qnil;
}