| In: |
./object.c
./lib/yaml.rb |
ryan: You know how Kernel.p is a really convenient way to dump ruby
structures? The only downside is that it's not as legible as
YAML.
_why: (listening)
ryan: I know you don’t want to urinate all over your users’ namespaces.
But, on the other hand, convenience of dumping for debugging is,
IMO, a big YAML use case.
_why: Go nuts! Have a pony parade!
ryan: Either way, I certainly will have a pony parade.
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 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
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
Converts arg to a String by calling its to_s method.
String(self) #=> "main" String(self.class #=> "Object" String(123456) #=> "123456"
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
Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.
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
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 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 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"
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.
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"]
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
Equivalent to $_ = $_.chomp(string). See String#chomp.
$_ = "now\n" chomp #=> "now" $_ #=> "now" chomp "ow" #=> "n" $_ #=> "n" chomp "xxx" #=> "n" $_ #=> "n"
Equivalent to $_.chomp!(string). See String#chomp!
$_ = "now\n" chomp! #=> "now" $_ #=> "now" chomp! "x" #=> nil $_ #=> "now"
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"
Equivalent to $_.chop!.
a = "now\r\n" $_ = a chop! #=> "now" chop! #=> "no" chop! #=> "n" chop! #=> "" chop! #=> nil $_ #=> "" a #=> ""
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"
no-op ;
new_argv = ALLOCA_N(char*, n + 2);
for (; n > 0; n--)
new_argv[n + 1] = argv[n];
new_argv[1] = strcpy(ALLOCA_N(char, strlen(argv[0]) + 1), argv[0]);
for (p = new_argv[1]; *p != '\0'; p++)
if (*p == '/')
p = '\\';
new_argv[0] = COMMAND;
argv = new_argv;
prog = dln_find_exe(argv[0], 0);
if (!prog) {
errno = ENOENT;
return -1;
}
}
endif
before_exec();
if defined(_WIN32)
status = do_aspawn(P_WAIT, prog, argv);
else
status = spawnv(P_WAIT, prog, argv);
endif
after_exec();
return status;
}
static int proc_spawn_n(argc, argv, prog)
int argc;
VALUE *argv;
VALUE prog;
{
char **args;
int i;
args = ALLOCA_N(char*, argc + 1);
for (i = 0; i < argc; i++) {
SafeStringValue(argv[i]);
args[i] = RSTRING(argv[i])->ptr;
}
if (prog)
SafeStringValue(prog);
args[i] = (char*) 0;
if (args[0])
return proc_spawn_v(args, prog ? RSTRING(prog)->ptr : 0);
return -1;
}
if !defined(_WIN32) static int proc_spawn(sv)
VALUE sv;
{
char *str;
char *s, *t;
char **argv, **a;
int status;
SafeStringValue(sv);
str = s = RSTRING(sv)->ptr;
for (s = str; *s; s++) {
if (*s != ' ' && !ISALPHA(*s) && strchr("*?{}[]<>()~&|\\$;'`\"\n",*s)) {
char *shell = dln_find_exe("sh", 0);
before_exec();
status = shell?spawnl(P_WAIT,shell,"sh","-c",str,(char*)NULL):system(str);
after_exec();
return status;
}
}
a = argv = ALLOCA_N(char*, (s - str) / 2 + 2);
s = ALLOCA_N(char, s - str + 1);
strcpy(s, str);
if (*a++ = strtok(s, " \t")) {
while (t = strtok(NULL, " \t"))
a++ = t;
a = NULL;
}
return argv[0] ? proc_spawn_v(argv, 0) : -1;
} endif endif
/*
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
/
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
Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.
Process.exit!(0)
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
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.
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"
Equivalent to Kernel::gsub, except nil is returned if $_ is not modified.
$_ = "quick brown fox" gsub! /cat/, '*' #=> nil $_ #=> "quick brown fox"
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"
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
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 the names of the current local variables.
fred = 1
for i in 1..10
# ...
end
local_variables #=> ["fred", "i"]
Repeatedly executes the block.
loop do
print "Input: "
line = gets
break if !line or line =~ /^qQ/
# ...
end
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 possibe 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
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 always returns nil in this case.
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
For each object, directly writes obj.inspect followed by the current output record separator to the program’s standard output. p bypasses the Ruby I/O libraries.
S = Struct.new(:name, :state) s = S['dave', 'TX'] p s
produces:
#<S name="dave", state="TX">
Prints each object in turn to $defout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($</code>) is not nil, it will be appended to the output. If no arguments are given, prints <code>$_. 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
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
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
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 219937-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 an array containing the lines returned by calling Kernel.gets(aString) until the end of file.
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"
See Kernel#select.
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
Suspends the current thread for duraction 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 the thread was interrupted by a SIGALRM, or if another thread calls Thread#run. An argument of zero 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
Seeds the pseudorandom number generator to the value of number.to_i.abs. If number is omitted or zero, 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.
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
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 *
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 files 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 files exists and is a symbolic link
?M | Time | Last modification time for file1
?o | boolean | True if files 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 files 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 is a hard link to file2
?= | 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
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.
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