Module: Kernel
- Included in:
- Object
- Defined in:
- object.c
Instance Method Summary collapse
-
#__method__ ⇒ Object
Returns the name of the current method as a Symbol.
-
#abort ⇒ Object
Terminate execution immediately, effectively by calling
Kernel.exit(1)
. -
#Array(arg) ⇒ Array
Returns arg as an
Array
. -
#at_exit { ... } ⇒ Proc
Converts block to a
Proc
object (and therefore binds it at the point of call) and registers it for execution when the program exits. -
#autoload ⇒ nil
Registers filename to be loaded (using
Kernel::require
) the first time that module (which may be aString
or a symbol) is accessed. -
#autoload ⇒ nil
Registers filename to be loaded (using
Kernel::require
) the first time that module (which may be aString
or a symbol) is accessed. -
#binding ⇒ Binding
Returns a
Binding
object, describing the variable and method bindings at the point of call. -
#block_given? ⇒ Object
Returns
true
ifyield
would execute a block in the current context. -
#callcc {|cont| ... } ⇒ Object
Generates a
Continuation
object, which it passes to the associated block. -
#caller(start = 1) ⇒ Array
Returns the current execution stack—an array containing strings in the form “file:line” or “file:line: in ‘method’”.
- #catch ⇒ Object
-
#chomp ⇒ Object
Equivalent to
$_ = $_.chomp(string)
. -
#chomp! ⇒ Object
Equivalent to
$_.chomp!(string)
. -
#chop ⇒ String
Equivalent to
($_.dup).chop!
, exceptnil
is never returned. -
#chop! ⇒ nil
Equivalent to
$_.chop!
. -
#eval(string[, binding [, filename [,lineno]]]) ⇒ Object
Evaluates the Ruby expression(s) in string.
-
#exit ⇒ Object
Initiates the termination of the Ruby script by raising the
SystemExit
exception. -
#fail ⇒ Object
With no arguments, raises the exception in
$!
or raises aRuntimeError
if$!
isnil
. -
#Float(arg) ⇒ Float
Returns arg converted to a float.
-
#format ⇒ Object
Returns the string resulting from applying format_string to any additional arguments.
-
#global_variables ⇒ Array
Returns an array of the names of global variables.
-
#gsub ⇒ Object
Equivalent to
$_.gsub...
, except that$_
receives the modified result. -
#gsub! ⇒ Object
Equivalent to
Kernel::gsub
, exceptnil
is returned if$_
is not modified. -
#Integer(arg) ⇒ Integer
Converts arg to a
Fixnum
orBignum
. -
#iterator? ⇒ Object
Returns
true
ifyield
would execute a block in the current context. -
#lambda ⇒ Object
Equivalent to
Proc.new
, except the resulting Proc objects check the number of parameters passed when called. -
#load(filename, wrap = false) ⇒ true
Loads and executes the Ruby program in the file filename.
-
#local_variables ⇒ Array
Returns the names of the current local variables.
-
#loop { ... } ⇒ Object
Repeatedly executes the block.
-
#method_missing(symbol[, *args]) ⇒ Object
Invoked by Ruby when obj is sent a message it cannot handle.
-
#proc ⇒ Object
Equivalent to
Proc.new
, except the resulting Proc objects check the number of parameters passed when called. -
#raise ⇒ Object
With no arguments, raises the exception in
$!
or raises aRuntimeError
if$!
isnil
. -
#rand(max = 0) ⇒ Numeric
Converts max to an integer using max1 = max
.to_i.abs
. -
#require(string) ⇒ Boolean
Ruby tries to load the library named string, returning
true
if successful. -
#scan ⇒ Object
Equivalent to calling
$_.scan
. -
#set_trace_func ⇒ Object
Establishes proc as the handler for tracing, or disables tracing if the parameter is
nil
. -
#split([pattern [, limit]]) ⇒ Array
Equivalent to
$_.split(pattern, limit)
. -
#sprintf ⇒ Object
Returns the string resulting from applying format_string to any additional arguments.
-
#srand(number = 0) ⇒ Object
Seeds the pseudorandom number generator to the value of number.
to_i.abs
. -
#String(arg) ⇒ String
Converts arg to a
String
by calling itsto_s
method. -
#sub ⇒ Object
Equivalent to
$_.sub(args)
, except that$_
will be updated if substitution occurs. -
#sub! ⇒ Object
Equivalent to
$_.sub!(args)
. -
#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).
- #throw ⇒ Object
-
#trace_var ⇒ Object
Controls tracing of assignments to global variables.
-
#trap ⇒ Object
Specifies the handling of signals.
-
#untrace_var(symbol[, cmd]) ⇒ Array?
Removes tracing for the specified command on the given global variable and returns
nil
. -
#warn(msg) ⇒ nil
Display the given message (followed by a newline) on STDERR unless warnings are disabled (for example with the
-W0
flag).
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
5633 5634 5635 |
# File 'eval.c', line 5633 static VALUE rb_method_missing(argc, argv, obj) int argc; |
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 foo
foo # => :foo
# => :foo
8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 |
# File 'eval.c', line 8130 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; } } |
#abort ⇒ Object #Kernel::abort ⇒ Object #Process::abort ⇒ Object
Terminate execution immediately, effectively by calling Kernel.exit(1)
. If msg is given, it is written to STDERR prior to terminating.
4536 4537 4538 |
# File 'eval.c', line 4536 VALUE rb_f_abort(argc, argv) int argc; |
#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]
2581 2582 2583 |
# File 'object.c', line 2581 static VALUE rb_f_array(obj, arg) VALUE obj, 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
8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 |
# File 'eval.c', line 8052 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; } |
#autoload ⇒ nil
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")
8306 8307 8308 |
# File 'eval.c', line 8306 static VALUE rb_f_autoload(obj, sym, file) VALUE obj; |
#autoload ⇒ nil
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")
8329 8330 8331 |
# File 'eval.c', line 8329 static VALUE rb_f_autoload_p(obj, sym) VALUE obj; |
#binding ⇒ 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"
8562 8563 8564 |
# File 'eval.c', line 8562 static VALUE rb_f_binding(self) VALUE self; |
#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"
4790 4791 4792 4793 4794 4795 4796 |
# File 'eval.c', line 4790 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.
13021 13022 13023 |
# File 'eval.c', line 13021 static VALUE rb_callcc(self) VALUE self; |
#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"]
6401 6402 6403 |
# File 'eval.c', line 6401 static VALUE rb_f_caller(argc, argv) int argc; |
#catch ⇒ Object
#chomp ⇒ Object #chomp(string) ⇒ Object
Equivalent to $_ = $_.chomp(string)
. See String#chomp
.
$_ = "now\n"
chomp #=> "now"
$_ #=> "now"
chomp "ow" #=> "n"
$_ #=> "n"
chomp "xxx" #=> "n"
$_ #=> "n"
4137 4138 4139 |
# File 'string.c', line 4137 static VALUE rb_f_chomp(argc, argv) int argc; |
#chomp! ⇒ nil #chomp!(string) ⇒ nil
Equivalent to $_.chomp!(string)
. See String#chomp!
$_ = "now\n"
chomp! #=> "now"
$_ #=> "now"
chomp! "x" #=> nil
$_ #=> "now"
4112 4113 4114 |
# File 'string.c', line 4112 static VALUE rb_f_chomp_bang(argc, argv) int argc; |
#chop ⇒ String
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"
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 |
# File 'string.c', line 3972 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 #=> ""
3947 3948 3949 |
# File 'string.c', line 3947 static VALUE rb_f_chop_bang(str) VALUE str; |
#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"
6625 6626 6627 |
# File 'eval.c', line 6625 static VALUE rb_f_eval(argc, argv, self) int argc; |
#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
4492 4493 4494 |
# File 'eval.c', line 4492 VALUE rb_f_exit(argc, argv) int argc; |
#raise ⇒ Object #raise(string) ⇒ Object #raise(exception[, string [, array]]) ⇒ Object #fail ⇒ Object #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
4678 4679 4680 |
# File 'eval.c', line 4678 static VALUE rb_f_raise(argc, argv) int argc; |
#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
2482 2483 2484 |
# File 'object.c', line 2482 static VALUE rb_f_float(obj, arg) VALUE obj, arg; |
#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"
247 248 249 |
# File 'sprintf.c', line 247 VALUE rb_f_sprintf(argc, argv) int argc; |
#global_variables ⇒ Array
Returns an array of the names of global variables.
global_variables.grep /std/ #=> ["$stderr", "$stdout", "$stdin"]
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 |
# File 'variable.c', line 787 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"
2414 2415 2416 |
# File 'string.c', line 2414 static VALUE rb_f_gsub(argc, argv) int argc; |
#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"
2393 2394 2395 |
# File 'string.c', line 2393 static VALUE rb_f_gsub_bang(argc, argv) int argc; |
#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
2329 2330 2331 |
# File 'object.c', line 2329 static VALUE rb_f_integer(obj, arg) VALUE obj, 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"
4790 4791 4792 4793 4794 4795 4796 |
# File 'eval.c', line 4790 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.
8760 8761 8762 8763 8764 |
# File 'eval.c', line 8760 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.
7087 7088 7089 |
# File 'eval.c', line 7087 static VALUE rb_f_load(argc, argv) int argc; |
#local_variables ⇒ Array
Returns the names of the current local variables.
fred = 1
for i in 1..10
# ...
end
local_variables #=> ["fred", "i"]
7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 |
# File 'eval.c', line 7925 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.
5218 5219 5220 5221 5222 5223 |
# File 'eval.c', line 5218 static VALUE rb_f_loop() { rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0); return Qnil; /* dummy */ } |
#proc {|...| ... } ⇒ Proc #lambda {|...| ... } ⇒ Proc
Equivalent to Proc.new
, except the resulting Proc objects check the number of parameters passed when called.
8760 8761 8762 8763 8764 |
# File 'eval.c', line 8760 static VALUE proc_lambda() { return proc_alloc(rb_cProc, Qtrue); } |
#raise ⇒ Object #raise(string) ⇒ Object #raise(exception[, string [, array]]) ⇒ Object #fail ⇒ Object #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
4678 4679 4680 |
# File 'eval.c', line 4678 static VALUE rb_f_raise(argc, argv) int argc; |
#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]
438 439 440 |
# File 'random.c', line 438 static VALUE rb_f_rand(argc, argv, obj) int argc; |
#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"
7273 7274 7275 |
# File 'eval.c', line 7273 VALUE rb_f_require(obj, fname) VALUE obj, fname; |
#scan(pattern) ⇒ Array #scan(pattern) {|///| ... } ⇒ Object
Equivalent to calling $_.scan
. See String#scan
.
4416 4417 4418 |
# File 'string.c', line 4416 static VALUE rb_f_scan(self, pat) VALUE self, pat; |
#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
2650 2651 2652 |
# File 'eval.c', line 2650 static VALUE set_trace_func(obj, trace) VALUE obj, trace; |
#split([pattern [, limit]]) ⇒ Array
Equivalent to $_.split(pattern, limit)
. See String#split
.
3681 3682 3683 |
# File 'string.c', line 3681 static VALUE rb_f_split(argc, argv) int argc; |
#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"
247 248 249 |
# File 'sprintf.c', line 247 VALUE rb_f_sprintf(argc, argv) int argc; |
#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
.
322 323 324 |
# File 'random.c', line 322 static VALUE rb_f_srand(argc, argv, obj) int argc; |
#String(arg) ⇒ String
Converts arg to a String
by calling its to_s
method.
String(self) #=> "main"
String(self.class #=> "Object"
String(123456) #=> "123456"
2545 2546 2547 |
# File 'object.c', line 2545 static VALUE rb_f_string(obj, arg) VALUE obj, arg; |
#sub(pattern, replacement) ⇒ Object #sub(pattern) { ... } ⇒ Object
Equivalent to $_.sub(args)
, except that $_
will be updated if substitution occurs.
2367 2368 2369 |
# File 'string.c', line 2367 static VALUE rb_f_sub(argc, argv) int argc; |
#sub!(pattern, replacement) ⇒ nil #sub!(pattern) {|...| ... } ⇒ nil
Equivalent to $_.sub!(args)
.
2350 2351 2352 |
# File 'string.c', line 2350 static VALUE rb_f_sub_bang(argc, argv) int argc; |
#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
3495 3496 3497 |
# File 'file.c', line 3495 static VALUE rb_f_test(argc, argv) int argc; |
#throw ⇒ Object
#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'
576 577 578 |
# File 'variable.c', line 576 VALUE rb_f_trace_var(argc, argv) int argc; |
#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
893 894 895 |
# File 'signal.c', line 893 static VALUE sig_trap(argc, argv) int argc; |
#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.
639 640 641 |
# File 'variable.c', line 639 VALUE rb_f_untrace_var(argc, argv) int argc; |
#warn(msg) ⇒ nil
Display the given message (followed by a newline) on STDERR unless warnings are disabled (for example with the -W0
flag).
180 181 182 |
# File 'error.c', line 180 static VALUE rb_warn_m(self, mesg) VALUE self, mesg; |