Welcome to Scribd. Sign in or start your free trial to enjoy unlimited e-books, audiobooks & documents.Find out more
Download
Standard view
Full view
of .
Look up keyword
Like this
8Activity
0 of .
Results for:
No results containing your search query
P. 1
ruby cheat sheet

ruby cheat sheet

Ratings:

4.6

(1)
|Views: 3,055|Likes:
Published by matthieutc

More info:

Published by: matthieutc on Feb 08, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as TXT, PDF, TXT or read online from Scribd
See more
See less

03/20/2013

pdf

text

original

 
Strings-------------------------"" #expansionString.new #constructor'' #no expansion%{} #keeps formatting%q{} #keeps formatting no expansion%w{a b c} #returns an array of strings no expansionstring = <<EOF #here documentRegexes-------------------------/literal/%r{literal}Regexp.new 'pattern' #string or literalRegexp#match 'string'=~ returns an index or nilif the pattern has groups, $1, $2, etc.. can be used to reference them after amatchCharacter 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:mmmd = re.match("Time: 12:34am")md.class ? MatchDatamd[0] # == $& ? "12:34"md[1] # == $1 ? "12"md[2] # == $2 ? "34"md.pre_match # == $` ? "Time: "md.post_match # == $' ? "am"Inheritance and modules-------------------------Module and class names must start with a capital letterYou can use modules as namespacesTo call a function in a module, use Module::func or Module.func or even::Module::func and ::Module.func (bug?)Use Object#extend to include modules programmaticallyRequires
 
-------------------------'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 extensionboth look at $: for the specified file'require' can load shared binary librarieslocal vars aren't propagatedboth method calls are in Kernel and can be part of the code logicload takes an extra parameter (wrap). When true, it executes the code in ananonymous module.Files and directories-------------------------File.file? checks if the arg is a real fileFile.exists? checks if the arg exists at all (might be a dir or a special file)You also have directory? socket? symlink? pipe?You can check permissions on a file with readable? writable? executable?Use Dir.entries and Dir.foreach to process the files in a dirYou can also use Dir[expr] to grab an array of the files matching expr, where expris about the same as the shell's rulesDir[expr] can load directory trees (** = any number of dirs)Reading files from a directory will empty the data stream. You need to call#rewind on it to get the files backUse Kernel#open('file').each {|line| puts line} #to iterate over each line (u needto close the file afterward)Use Kernel#open('file') {|file| f.readlines } #to load all the lines of the filein an arrayUse File#open('file', 'flags'){|f| f.puts 'asdasd'} #to write to a file quicklymode strings to use with Kernel#open or IO#openr Read-only, starts at beginning of file (default mode).r+ Read/write, starts at beginning of file.w Write-only, truncates an existing file to zero length or creates a new filefor writingw+ Read/write, truncates existing file to zero length or creates a new file forreading and writing.a Write-only, starts at end of file if file exists; otherwise creates a new filefor writing.a+ Read/write, starts at end of file if file exists; otherwise creates a newfile for reading and writing.b (DOS/Windows only) Binary file mode (may appear with any of the key letterslisted above).You can get a lock on a file using File#flock(File::LOCK_(SH|EX|NB|UN))Use StringIO to treat a string as a fileOther methods of interest:FileUtils.touchDir.mkdir
 
FileUtils.remove_dirDir.getwdDir.chdirThe 'find' library contains methods to find files in a treeException Handling-------------------------begin#dangerous coderescue Exception => e #dont use global vars (are they thread local?)#healing coderetry #goes back to beginelse#gets here if no exception occurredensure#finally blockend#Use throw and catch to get out of multiple loops or to make sure exceptionhandling 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 argumentcatch (:done) dowhile line = getsthrow :done unless fields = line.split(/\t/)songlist.add(Song.new(*fields))endsonglist.playendWhen rescuing, if you do not specify an exception class, the default isStandardErrorWhen rescuing, ruby looks for the rescue block rescuing the exception class or anyof its parentsif you just call raise, you're raising $! or a RuntimeError (use it to raise $!only though)raise has an alias 'fail'raise is in KernelReflection------------------------ancestors #returns a list of classes and modules inherited including theclass/module itselfmethods #all the publicly accessible methods (use on the class of anobject to get class methods)undef_method #prevents the current class from responding to the method inarg (a symbol)remove_method #prevents the current class from responding to the method inarg (a symbol) but ruby will still look in the parent classesinstance_methodsinstance_variablessingleton_methods...and a slew of other methods to get methods

Activity (8)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
Douglas Roaden liked this
sm255 liked this
Michael Tremel liked this
semmons99 liked this
feakk liked this
Marely Del Valle liked this

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->