Difference between revisions of "Ruby Notes"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
(26 intermediate revisions by the same user not shown) | |||
Line 4: | Line 4: | ||
* [http://www.ruby-lang.org/en/documentation/quickstart/ Quick Start] | * [http://www.ruby-lang.org/en/documentation/quickstart/ Quick Start] | ||
* [http://en.wikibooks.org/wiki/Ruby_Programming WikiBooks.org Ruby manual] | * [http://en.wikibooks.org/wiki/Ruby_Programming WikiBooks.org Ruby manual] | ||
* [http://en.wikibooks.org/wiki/Ruby_Programming/Reference Ruby Programming Reference] | |||
=Source of Gems= | |||
* http://rubyforge.iasi.roedu.net/gems/ | |||
=Variables= | |||
* http://www.tutorialspoint.com/ruby/ruby_variables.htm | |||
==Naming Conventions== | |||
{|style="color:blue; background-color:#ffddcc;" cellpadding="2" cellspacing="0" border="1" | |||
!Name Begins With | |||
!Variable Scope | |||
|- style="font-style:italic; color:green;" | |||
|$ | |||
|A global variable | |||
|- | |||
|@ | |||
|An instance variable | |||
|- | |||
|[a-z] or _ | |||
|A local variable | |||
|- | |||
|[A-Z] | |||
|A constant | |||
|- | |||
|@@ | |||
|A class variable | |||
|} | |||
==$ Variables== | |||
{|style="color:blue; background-color:#ffffcc;" cellpadding="2" cellspacing="0" border="1" | |||
!Variable Name | |||
!Variable Value | |||
|- | |||
|$@||The location of latest error | |||
|- | |||
|$_ ||The string last read by gets | |||
|- | |||
|$. ||The line number last read by interpreter | |||
|- | |||
|$& ||The string last matched by regexp | |||
|- | |||
|$~ ||The last regexp match, as an array of subexpressions | |||
|- | |||
|$n ||The nth subexpression in the last match (same as $~[n]) | |||
|- | |||
|$= ||The case-insensitivity flag | |||
|- | |||
|$/ ||The input record separator | |||
|- | |||
|$\ ||The output record separator | |||
|- | |||
|$0 ||The name of the ruby script file currently executing | |||
|- | |||
|$* ||The command line arguments used to invoke the script | |||
|- | |||
|$$ ||The Ruby interpreter's process ID | |||
|- | |||
|$? ||The exit status of last executed child process | |||
|- | |||
|} | |||
=Class vs. Instance Variables= | =Class vs. Instance Variables= | ||
Here are a few reference on the subject... | |||
* http://www.rubycentral.com/pickaxe/tut_classes.html | * http://www.rubycentral.com/pickaxe/tut_classes.html | ||
Line 11: | Line 79: | ||
* http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby | * http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby | ||
* http://martinfowler.com/bliki/ClassInstanceVariable.html | * http://martinfowler.com/bliki/ClassInstanceVariable.html | ||
* http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby | |||
The definition of the class instance variable is the fragment | The definition of the class instance variable is the fragment | ||
Line 17: | Line 86: | ||
This defines an instance variable (and getters and setters) on the class that's inherited by its descendents. Unlike class variables these class instance variables will take different values for each class object. | This defines an instance variable (and getters and setters) on the class that's inherited by its descendents. Unlike class variables these class instance variables will take different values for each class object. | ||
=String Functions= | |||
==To change case:== | |||
capitalize - first character to upper, rest to lower | |||
downcase - all to lower case | |||
swapcase - changes the case of all letters | |||
upcase - all to upper case | |||
==To rejustify:== | |||
center - add white space padding to center string | |||
ljust - pads string, left justified | |||
rjust - pads string, right justified | |||
==To trim:== | |||
chop - remove last character | |||
chomp - remove trailing line separators | |||
squeeze - reduces successive equal characters to singles | |||
strip - deletes leading and trailing white space | |||
==To examine:== | |||
count - return a count of matches | |||
empty? - returns true if empty | |||
include? - is a specified target string present in the source? | |||
index - return the position of one string in another | |||
length or size - return the length of a string | |||
rindex - returns the last position of one string in another | |||
slice - returns a partial string | |||
==To encode and alter:== | |||
crypt - password encryption | |||
delete - delete an intersection | |||
dump - adds extra \ characters to escape specials | |||
hex - takes string as hex digits and returns number | |||
next or succ - successive or next string (eg ba -> bb) | |||
oct - take string as octal digits and returns number | |||
replace - replace one string with another | |||
reverse - turns the string around | |||
slice! - DELETES a partial string and returns the part deleted | |||
split - returns an array of partial strings exploded at separator | |||
sum - returns a checksum of the string | |||
to_f and to_i - return string converted to float and integer | |||
tr - to map all occurrences of specified char(s) to other char(s) | |||
tr_s - as tr, then squeeze out resultant duplicates | |||
unpack - to extract from a string into an array using a template | |||
==To iterate:== | |||
each - process each character in turn | |||
each_line - process each line in a string | |||
each_byte - process each byte in turn | |||
upto - iterate through successive strings (see "next" above) | |||
=append (<<) versus concat (+)= | |||
* http://almaer.com/blog/ruby-append | |||
=HTTP= | =HTTP= | ||
Line 102: | Line 232: | ||
</pre> | </pre> | ||
=Arrays= | |||
* http://ruby-doc.org/core/classes/Array.html | |||
* http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Containers_Blocks_and_Iterators_Implementing_a_SongList_Container.html | |||
=Files= | |||
* http://www.tutorialspoint.com/ruby/ruby_input_output.htm | |||
=Here Documents= | |||
A way of handling multi-line text in scripts | |||
* http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html | |||
=Enumerations= | |||
* http://ruby-doc.org/core/classes/Enumerable.html | |||
[[Category:ruby]] | [[Category:ruby]] | ||
[[Category:Examples]] | [[Category:Examples]] |
Latest revision as of 11:42, 18 March 2010
References
- http://www.ruby-lang.org/en/documentation/
- Quick Start
- WikiBooks.org Ruby manual
- Ruby Programming Reference
Source of Gems
Variables
Naming Conventions
Name Begins With | Variable Scope |
---|---|
$ | A global variable |
@ | An instance variable |
[a-z] or _ | A local variable |
[A-Z] | A constant |
@@ | A class variable |
$ Variables
Variable Name | Variable Value |
---|---|
$@ | The location of latest error |
$_ | The string last read by gets |
$. | The line number last read by interpreter |
$& | The string last matched by regexp |
$~ | The last regexp match, as an array of subexpressions |
$n | The nth subexpression in the last match (same as $~[n]) |
$= | The case-insensitivity flag |
$/ | The input record separator |
$\ | The output record separator |
$0 | The name of the ruby script file currently executing |
$* | The command line arguments used to invoke the script |
$$ | The Ruby interpreter's process ID |
$? | The exit status of last executed child process |
Class vs. Instance Variables
Here are a few reference on the subject...
- http://www.rubycentral.com/pickaxe/tut_classes.html
- http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes
- http://railstips.org/2006/11/18/class-and-instance-variables-in-ruby
- http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby
- http://martinfowler.com/bliki/ClassInstanceVariable.html
- http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby
The definition of the class instance variable is the fragment
class << self; attr_accessor :instances; end.
This defines an instance variable (and getters and setters) on the class that's inherited by its descendents. Unlike class variables these class instance variables will take different values for each class object.
String Functions
To change case:
capitalize - first character to upper, rest to lower downcase - all to lower case swapcase - changes the case of all letters upcase - all to upper case
To rejustify:
center - add white space padding to center string ljust - pads string, left justified rjust - pads string, right justified
To trim:
chop - remove last character chomp - remove trailing line separators squeeze - reduces successive equal characters to singles strip - deletes leading and trailing white space
To examine:
count - return a count of matches empty? - returns true if empty include? - is a specified target string present in the source? index - return the position of one string in another length or size - return the length of a string rindex - returns the last position of one string in another slice - returns a partial string
To encode and alter:
crypt - password encryption delete - delete an intersection dump - adds extra \ characters to escape specials hex - takes string as hex digits and returns number next or succ - successive or next string (eg ba -> bb) oct - take string as octal digits and returns number replace - replace one string with another reverse - turns the string around slice! - DELETES a partial string and returns the part deleted split - returns an array of partial strings exploded at separator sum - returns a checksum of the string to_f and to_i - return string converted to float and integer tr - to map all occurrences of specified char(s) to other char(s) tr_s - as tr, then squeeze out resultant duplicates unpack - to extract from a string into an array using a template
To iterate:
each - process each character in turn each_line - process each line in a string each_byte - process each byte in turn upto - iterate through successive strings (see "next" above)
append (<<) versus concat (+)
HTTP
Refactor
module Anubis module ShardAccess require "net/http" LIB_VERSION = 'r1b' class Read attr_accessor :path, :body, :headers def initialize( path_in, body_in, accept='xml', limit=10 ) self.path = path_in self.body = body_in self.headers = { 'Interface' => 'S1', 'Accept' => accept, 'Limit' => limit.to_s, 'Content-Type' => 'application/x-www-form-urlencoded', 'User-Agent' => 'RB_SHARD_ACCESS_LIB_' + Anubis::ShardAccess::LIB_VERSION } end def call ( host, port ) http = Net::HTTP.new( host, port ) resp = http.post2( @path, @body, @headers ) end end end end host = 'IP.AD.RE.SS' port = 10001 path = '/message' body = "query_string" req = Anubis::ShardAccess::Read.new( path, body, 'csv', 1 ) data = req.call( host, port ) puts data.body
to
# no need to put this within the module body as it will be loaded regardless require 'net/http' module Anubis module ShardAccess LIB_VERSION = 'r1b' class Read attr_accessor :path, :body, :headers #usually past a few args you should provide an options has to make things more readable # such as Read.new foo, bar, :accept => :csv, :limit => 1 def initialize path, body, options = {} @path, @body = path, body @headers = { 'Interface' => 'S1', 'Accept' => options.fetch(:accept, :xml), # Hash#fetch will use the keys value when found, otherwise the second argument is used (:xml) 'Limit' => options.fetch(:limit, 10), 'Content-Type' => 'application/x-www-form-urlencoded', 'User-Agent' => 'RB_SHARD_ACCESS_LIB_' + LIB_VERSION } end def call host, port Net::HTTP.new(host, port).post2 path, body, headers end end end end
Arrays
- http://ruby-doc.org/core/classes/Array.html
- http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Containers_Blocks_and_Iterators_Implementing_a_SongList_Container.html
Files
Here Documents
A way of handling multi-line text in scripts