Ruby Cheat Sheet
Ruby Cheat Sheet
-------------------------
"" #expansion
String.new #constructor
'' #no expansion
%{} #keeps formatting
%q{} #keeps formatting no expansion
%w{a b c} #returns an array of strings no expansion
string = <<EOF #here document
Regexes
-------------------------
/literal/
%r{literal}
Regexp.new 'pattern' #string or literal
Regexp#match 'string'
=~ returns an index or nil
if the pattern has groups, $1, $2, etc.. can be used to reference them after a
match
Character classes:
[:alnum:] Alphanumeric
[:alpha:] Uppercase or lowercase letter
[:blank:] Blank and tab
[:cntrl:] Control characters (at least 0x00?0x1f, 0x7f)
[:digit:] Digit
[:graph:] Printable character excluding space
[:lower:] Lowercase letter
[:print:] Any printable character (including space)
[:punct:] Printable character excluding space and alphanumeric
[:space:] Whitespace (same as \s)
[:upper:] Uppercase letter
[:xdigit:] Hex digit (0?9, a?f, A?F)
OO regexes:
re = /(\d+):(\d+)/ # match a time hh:mm
md = re.match("Time: 12:34am")
md.class ? MatchData
md[0] # == $& ? "12:34"
md[1] # == $1 ? "12"
md[2] # == $2 ? "34"
md.pre_match # == $` ? "Time: "
md.post_match # == $' ? "am"
Requires
-------------------------
'require' loads a file only once and takes the name of the file, with or without
.rb, and puts the file in $"
'load' loads a file unconditionnaly and needs the .rb extension
Reading files from a directory will empty the data stream. You need to call
#rewind on it to get the files back
Use Kernel#open('file').each {|line| puts line} #to iterate over each line (u need
to close the file afterward)
Use Kernel#open('file') {|file| f.readlines } #to load all the lines of the file
in an array
Use File#open('file', 'flags'){|f| f.puts 'asdasd'} #to write to a file quickly
Exception Handling
-------------------------
begin
#dangerous code
rescue Exception => e #dont use global vars (are they thread local?)
#healing code
retry #goes back to begin
else
#gets here if no exception occurred
ensure
#finally block
end
#Use throw and catch to get out of multiple loops or to make sure exception
handling is not used to carry the logic of your program
#After a catch(:sym){} ruby executes the given block and if it encounters a throw,
it goes up the food chain up to the appropriate catch.
#When the appropriate catch is found, execution continues after the block
#the symbol is given to the block in argument
catch (:done) do
while line = gets
throw :done unless fields = line.split(/\t/)
songlist.add(Song.new(*fields))
end
songlist.play
end
Reflection
------------------------
ancestors #returns a list of classes and modules inherited including the
class/module itself
methods #all the publicly accessible methods (use on the class of an
object to get class methods)
undef_method #prevents the current class from responding to the method in
arg (a symbol)
remove_method #prevents the current class from responding to the method in
arg (a symbol) but ruby will still look in the parent classes
instance_methods
instance_variables
singleton_methods
...and a slew of other methods to get methods
Call Object#method(:method_name) to get a Method object (then Method#call to call
it)
This function accepts a block explicitly (they can all accept blocks implicitly
and check for one using 'block_given?'):
def callme(&aBlock)
yield
end
Thread#join blocks until the receiver terminates. If given a timeout argument and
timeout occurs, join returns nil.
A similar method #value returns the value of the last statement
You can create per-thread variables, accessible from anywhere, by treating the
Thread object like a hash
Thread.current["var_name"] = 'value'
You might wanna call print 'string\n' instead of puts in a thread as puts is prone
to rescheduling mid-stream
Thread#stop and Thread#run can be used, though it's bad form, to stop and run
threads
You can also use the built-in Mutex and ConditionVariable classes
Easiest way to fork:
pid = fork do
puts 'im a child'
exit 1
end
#parent's code
#$?.exitstatus contains 1
After forking a child, Process.wait will wait and return the exit code while
Kernel#detach will detach
You can also setup a Signal#trap {} if you dont wanna wait but care about the
results
The child can use Kernel#exit! to exit without running any at_exit code
Scripting
------------------------
$* or ARGV #contains the arguments
ARGF #contains the program's input files (really ARGV
as if they were files)
output = %x{echo a} #runs the command in a subshell, returns output,
sets $?
output = `echo a` #ditto
true|false = system('echo a') #runs the command in a subshell, returns true if
successful, else false (single arg == shell expansion)
exec('echo a') #replaces the program with the command (single arg
== shell expansion)
eval("puts 'a'") #evaluates the ruby expression, also takes a binding
IO.popen #scripts external non-interactive programs (to use
stdin of the external program)
IO.popen("su -c 'echo /etc/passwd'", 'r+') do |io| #this does not work because
of restrictions on su -c
io.puts 'password'
io.close_write #you need to close write before you read
return io.read
end
Kernel#gets(separator=$/) will grab a line from $stdin or ARGF and returns nil at
EOF
Global variables
------------------------
$! latest error message (thread local)
$@ location of error (thread local)
$_ string last read by gets (local scope)
$/ input record separator (defaults to newline)
$-0 synonym for $/
$\ output record separator (defaults to nil)
$0 the name of the top level program
__FILE__ the name of the current source file
$$ interpreter's process ID
$fi exit status of last executed child process
$: path when looking for ruby files
$-I Synonym for $:. [r/o]
$LOAD_PATH A synonym for $:. [r/o]
$" a list of files that have been 'required'
$> destination of output for Kernel#print
$; default separator to String#split
$-F synonym for $;
$, separator used by Kernel#print and Array#join
ENV environment hash
__LINE__ The current line number in the source file. [r/o]
$SAFE The current safe level (see page 380). This variable's value may
never be reduced by assignment. [thread]
$binding only used by irb
::arguments::
$* the command line arguments
ARGV synonym for $*
$-a true if -a is specified on the CLI (autosplit)
$DEBUG true if -d is specified on the CLI
$-d synonym for $DEBUG
ARGF input files array
$< synonym for ARGF
$FILENAME The name of the current input file. Equivalent to $<.filename [r/o]
$. the number of the last line read from the current input file
$F The array that receives the split input line if the -a command-line
option is used.
$-i If in-place edit mode is enabled (perhaps using the -i command-line
option), $-i holds the extension used when creating the backup file. If you set a
value into $-i, enables in-place edit mode. See page 168.
$-K Sets the multibyte coding system for strings and regular
expressions. Equivalent to the -K command-line option. See page 169.
$-l Set to true if the -l option (which enables line-end processing) is
present on the command line. See page 169. [r/o]
$-p Set to true if the -p option (which puts an implicit while gets . .
. end loop around your program) is present on the command line. See page 169.
[r/o]
$VERBOSE Set to true if the -v, --version, -W, or -w option is specified on
the command line. Set to false if no option, or -W1 is given. Set to nil if -W0
was specified. Setting this option to true causes the interpreter and some library
routines to report additional information. Setting to nil suppresses all warnings
(including the output of Kernel.warn).
$-v Synonym for $VERBOSE.
$-w Synonym for $VERBOSE.
Notes
------------------------
only nil and false are considered false in a boolean context
Versions prior to 1.9 lack a character data type (compare to C, which provides
type char for characters). This may cause surprises when slicing strings: "abc"[0]
yields 97 (an integer, representing the ASCII code of the first character in the
string); to obtain "a" use "abc"[0,1] (a substring of length 1) or "abc"[0].chr
Safe levels (you can change them using the switch -T), more info on page 383:
0 No checking of the use of externally supplied (tainted) data is performed.
This is Ruby?s default mode.
>1 Ruby disallows the use of tainted data by potentially dangerous operations.
>2 Ruby prohibits the loading of program ?les from globally writable locations.
>3 All newly created objects are considered tainted.
>4 Ruby effectively partitions the running program in two. Nontainted objects
may not be modi?ed.