| FAQ and some useful tips | ||
![]() And only then your keywords will be indexed for searching. – HOME – go to the first, END – to the last, ESC – new search – Links are allowed only in body of description. To write link – just write it (no tags needed) – Don’t use the same keyword in description/code, then in the title and then in the keyword-line. |
||
sample Sample text block Some description of Ruby not sample... For the samples there is the right side of the page → All changes of sandbox will not appear on the original page and will not be visible for you after refresh. sample syntax def Syntax sample Description of sample syntax |
|
What is Ruby?
– Ruby is a reflective, dynamic, object-oriented programming language. It combines syntax inspired by Perl with Smalltalk-like object-oriented features, and also shares some features with Python, Lisp, Dylan and CLU. Ruby is a single-pass interpreted language. Its main implementation is free software. (en.wikipedia.org/wiki/Ruby_programming_language) – A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. (ruby-lang.org) – Ruby is a an exciting new, pure, object oriented programming language. While few people in the West have heard of Ruby yet, it has taken off like wildfire in Japan – already overtaking the Python language in popularity. (rubycentral.com) links, sites Resources ruby-lang.org – Ruby language home page rubycentral.org rubyforge.org – A SourceForge-like home for all kinds of Ruby projects ruby-doc.org/docs/ProgrammingRuby – An on-line copy of the first edition of the book Programming Ruby, by Dave Thomas. (ebook) ruby-doc.org - docs and online reference tryruby.hobix.com – Try Ruby in your web browser rubycentral.com rubylearning.org - Free Online Ruby Course rubylearning.com – Learning Ruby Tutorial rubylearning.com/jobs/ruby_jobs.html - Ruby India Jobs rubycorner.com – Directory for blogs related to Ruby rubyrockstars.com – Ruby Jobs snippets.dzone.com/tag/ruby – public source code repository rubyonrails.com – open source web application framework "Ruby on Rails" written in the Ruby language (often shortened to "Rails", or "RoR") pleac.sourceforge.net/pleac_ruby – In this document, you'll find an implementation of the Solutions of the Perl Cookbook in the Ruby language. links Community groups.google.com/group/comp.lang.ruby – Google group: 5.4k members, 35k topics groups.google.com/group/ruby-talk-google – Google group: 771 members, 7.8k topics sitepoint.com/forums/forumdisplay.php?f=227 – SitePoint Ruby tech.groups.yahoo.com/group/puneruby - PuneRuby RUG ruby-forum.com – Forum List devpals.com/forumdisplay.php?f=6 – Even Ruby developers need help sometimes. Whether it be Rails or anything else, this is the place to find answers irc.freenode.net/#ruby-lang – the #ruby-lang irc channel averages 150+ users lingr.com/room/5Rfd8nM5tMF – Ruby Chat Room links Blogs rubyinside.com – dedicated to Ruby and its associated technologies, including Ruby on Rails rubygarden.org rubylearning.com/blog - Learning Ruby blog redhanded.hobix.com - Why's Ruby Blog Advantages – Reflection. As well as supporting reflection into both classes and individual objects, Ruby lets you traverse the list of currently active objects. – Marshalling. Ruby objects can be serialized and deserialized, allowing them to be saved externally and transmitted across networks. A full distributed object system, DRb, is written in about 200 lines of Ruby code. – Libraries. Ruby has a large (and growing) collection of libraries. All major Internet protocols are supported, as are most major databases. Extending Ruby is simple compared with (say) Perl. – Threads. Ruby has built-in support for threads, and doesn’t rely on the underlying operating system for thread support. – Object specialization. You can add methods to individual objects, not just classes. This can be useful when defining specialized behavior for objects (for example, determining how they respond to GUI events). – Exceptions. Ruby has a fully object-oriented, extensible exception model. | |
|
|
# comment Single line comment | comment # Ruby treats nil as a false value in conditions, # you could write the following to process the lines in a file. |
Assignment – An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue). It then returns that value as the result of the assignment expression. This means you can chain assignments, and you can perform assignments in some unexpected places. – In older Ruby versions, the result of the assignment was the value returned by the attribute-setting method. In Ruby 1.8, the value of the assignment is always the value of the parameter; the return value of the method is discarded. – Ruby assignments are effectively performed in parallel, so the values assigned are not affected by the assignment itself. The values on the right side are evaluated in the order in which they appear before any assignment is made to variables or attributes on the left. – When an assignment has more than one lvalue, the assignment expression returns an array of the rvalues. If an assignment contains more lvalues than rvalues, the excess lvalues are set to nil. If a multiple assignment contains more rvalues than lvalues, the extra rvalues are ignored. If an assignment has just one lvalue and multiple rvalues, the rvalues are converted to an array and assigned to the lvalue. – In common with many other languages, Ruby has a syntactic shortcut: a = a + 2 may be written as a += 2. – Something you won’t find in Ruby are the autoincrement (++) and autodecrement (--) operators of C and Java. Use the += and -= forms instead. | return value of the method is discarded class Test def val=(val) #creates only writable member of class @val = val return 99 end end t = Test.new a = t.val = 2 a #-->2 |
Returning Anything that can reasonably return a value does. The if and case statements both return the value of the last expression executed | returning a = b = c = 0 #--> 0 a = b = 1 + 2 + 3 a #-->6 b #-->6 a = (b = 1 + 2) + 3 a #-->6 b #-->3 File.open(name = gets.chomp) [ 3, 1, 7, 0 ].sort.reverse #-->[7, 3, 1, 0] if returns song_type = if song.mp3_type == MP3::Jazz if song.written < Date.new(1935, 1, 1) Song::TradJazz else Song::Jazz end else Song::Other end if returns in next lines wer = if (false) 1 else 2 end puts wer #-> 2 case returns rating = case votes_cast when 0...10 then Rating::SkipThisOne when 10...50 then Rating::CouldDoBetter else Rating::Rave end
conditions returns part = [0, 1] puts val = part && part[1] || '1' #-> 1 puts val = part && part[2] || '2' #-> 2 |
Parallel assignment An assignment expression may have one or more lvalues and one or more rvalues. This section explains how Ruby handles assignment with different combinations of arguments. 1. If the last rvalue is prefixed with an asterisk and is an object of class Array, the rvalue is replaced with the elements of the array, with each element forming its own rvalue. 2. If the assignment contains multiple lvalues and one rvalue, the rvalue is converted into an Array, and this array is expanded into a set of rvalues as described in (1). 3. Successive rvalues are assigned to the lvalues. This assignment effectively happens in parallel, so that (for example) a,b=b,a swaps the values in "a" and "b." 4. If there are more lvalues than rvalues, the excess will have nil assigned to them. 5. If there are more rvalues that lvalues, the excess will be ignored. 6. These rules are modified slightly if the last lvalue is preceded with an asterisk. This lvalue will always receive an array during the assignment. The array will consist of whatever rvalue would normally have been assigned to this lvalue, followed by the excess rvalues (if any). 7. If an lvalue is a parenthesized list, it is treated as a nested assignment statement, and the list is assigned from the corresponding rvalue as described by these rules. Collapse and expand arrays using parallel assignment You can collapse and expand arrays using Ruby’s parallel assignment operator. If the last lvalue is preceded by an asterisk, all the remaining rvalues will be collected and assigned to that lvalue as an array. Similarly, if the last rvalue is an array, you can prefix it with an asterisk, which effectively expands it into its constituent values in place. (This is not necessary if the rvalue is the only thing on the right side—the array will be expanded automatically.) | parallel assignment a, b = b, a #swap the values in two variables x = 0 #-> 0 a, b, c = x, (x += 1), (x += 1) #-> [0, 1, 2] a, b, c = 1, "cat", [ 3, 4, 5 ] a = [1, 2, 3, 4] b, c = a #-> b == 1, c == 2 b, *c = a #-> b == 1, c == [2, 3, 4] b, c = 99, a #-> b == 99, c == [1, 2, 3, 4] b, *c = 99, a #-> b == 99, c == [[1, 2, 3, 4]] b, c = 99, *a #-> b == 99, c == 1 b, *c = 99, *a #-> b == 99, c == [1, 2, 3, 4] |
Nested assignments Parallel assignments have one more feature worth mentioning. The left-hand side of an assignment may contain a parenthesized list of terms. Ruby treats these terms as if they were a nested assignment statement. It extracts out the corresponding rvalue, assigning it to the parenthesized terms, before continuing with the higher-level assignment. | nested assignments b, (c, d), e = 1,2,3,4 #-> b == 1, c == 2, d == nil, e == 3 b, (c, d), e = [1,2,3,4] #-> b == 1, c == 2, d == nil, e == 3 b, (c, d), e = 1,[2,3],4 #-> b == 1, c == 2, d == 3, e == 4 b, (c, d), e = 1,[2,3,4],5 #-> b == 1, c == 2, d == 3, e == 5 b, (c,*d), e = 1,[2,3,4],5 #-> b == 1, c == 2, d == [3, 4], e == 5 |
Comparison == Test for equal value. === Used to compare the each of the items with the target in the when clause of a case statement. <=> General comparison operator. Returns -1, 0, or +1, depending on whether its receiver is less than, equal to, or greater than its argument. <, <=, >=, > Comparison operators for less than, less than or equal, greater than or equal, and greater than. =~ Regular expression pattern match. eql? True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false. equal? True if the receiver and argument have the same object ID. – Both == and =~ have negated forms, != and !~. However, these are converted by Ruby when your program is read. a != b is equivalent to !(a == b), and a !~ b is the same as !(a =~ b). This means that if you write a class that overrides == or =~ you get a working != and !~ for free. But on the flip side, this also means that you cannot define != and !~ independent of == and =~, respectively. – You can use a Ruby range as a boolean expression. A range such as exp1..exp2 will evaluate as false until exp1 becomes true. The range will then evaluate as true until exp2 becomes true. Once this happens, the range resets, ready to fire again. We show some examples of this on page | |
document here, here document Here document A here document consists of lines in the source up to, but not including, the terminating string that you specify after the << characters. Normally, this terminator must start in the first column. However, if you put a minus sign after the << characters (<<-), you can indent the terminator. Strings can continue across multiple input lines, in which case they will contain newline characters. It is also possible to use here documents to express long string literals. Whenever Ruby parses the sequence <<identifier or <<quoted string, it replaces it with a string literal built from successive logical input lines. It stops building the string when it finds a line that starts with the identifier or the quoted string. You can put a minus sign immediately after the << characters, in which case the terminator can be indented from the left margin. If a quoted string was used to specify the terminator, its quoting rules will be applied to the here document; otherwise, double-quoting rules apply. | here document aString = <<END_OF_STRING The body of the string is the input lines up to one ending with the same text that followed the '<<' END_OF_STRING indent the terminator print <<-STRING1, <<-STRING2 Concat STRING1 enate STRING2 produces: Concat enate
quoting rules
a = 123
print <<HERE
Double quoted \
here document.
Sum = #{a + 1}
HERE
print <<-'THERE'
This is single quoted.
The above used #{a + 1}
THERE
produces: Double quoted here document.
Sum = 124
This is single quoted.
The above used #{a + 1}
|
null nil Object, just like any other, that happens to represent nothing. spaceship <=> Compares two values, returning -1, 0, or +1 depending on whether the first is less than, equal to, or greater than the second. | |
$_ variable Global variable $_ |
This uses some behind-the-scenes magic behavior: gets assigns the last line read to the global variable $_, the ~ operator does a regular expression match against $_, and print with no arguments prints $_.
file = File.open("ordinal")
while file.gets
print if ~/third/ .. ~/fifth/
end
|
BEGIN and END Blocks Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks). – A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order. |
BEGIN & END blocks
BEGIN {puts "begin code 1"}
END {puts "end code 1"}
puts "line 2"
BEGIN {puts "begin code 2"}
END {puts "end code 2"}
puts "line 3"
produces:
begin code 1
begin code 2
line 1
line 2
line 3
end code 2
end code 1
|
General Delimited Input There are alternative forms of literal strings, arrays, regular expressions, and shell commands that are specified using a generalized delimited syntax.
– All these literals start with a percent character, followed by a single character that identifies the literal's type.
– Following the type character is a delimiter, which can be any character.
– If the delimiter is one of the characters "(", "[", "{", or "<", the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character.
– Delimited strings may continue over multiple lines.
%q – Single-quoted string
%Q, % – Double-quoted string
%w – Array of tokens
%W – Array of tokens with substitutions
%r – Regular expression pattern
%x – Shell command |
using
var = 'Exp'
%q/this is a string #{var}/ #-> this is a string #{var}
%Q-string #{var}- #-> string Exp
%(a (nested) string var=#{var}) #-> a (nested) string var=Exp
(%w<q va\ r e r t y>)[1] #-> va r
['q', var, 'e', 'r', 't', 'y'][1] #-> Exp
puts %q{def fred(a)
a.each { |i| puts i }
end}
produces:
def fred(a)
a.each { |i| puts i }
end
%w %W samples
value = 1
a = %w{ #{value} } # => ["\#{value}"]
b = %W{ #{value} } # => ["1"]
|
: Symbols A Ruby symbol is the internal representation of a name. You construct the symbol for a name by preceding the name with a colon. – A particular name will always generate the same symbol, regardless of how that name is used within the program. – Other languages call this process "interning" and call symbols "atoms". | symbols :Object :myVariable |
0 Conditional Execution – Ruby has a simple definition of truth. Any value that is not nil or the constant false is true. – However, C, C++, and Perl programmers sometimes fall into a trap. The number zero is not interpreted as a false value. Neither is a zero-length string. This can be a tough habit to break. |
|
The Value of Logical Expressions – In the text, we said things such as "and evaluates to true if both operands are true." But it’s actually slightly more subtle than that. The operators and, or, && and || actually return the first of their arguments that determine the truth or falsity of the condition. Sounds grand.What does it mean? Take the expression "val1 and val2". If val1 is either false or nil, then we know the expression cannot be true. In this case, the value of val1 determines the overall value of the expression, so it is the value returned. If val1 has some other value, then the overall value of the expression depends on val2, so its value is returned. – Note that despite all this magic, the overall truth value of the expression is correct. – The same evaluation takes place for or (except an or expression’s value is known early if val1 is not false). | and nil and true #-->nil false and true #-->false 99 and false #-->false 99 and nil #-->nil 99 and "cat" #-->"cat" |
&&, and Both and and && evaluate to true only if both operands are true. They evaluate the second operand only if the first is true (this is sometimes known as shortcircuit evaluation). The only difference in the two forms is precedence (and binds lower than &&). ||, or Similarly, both or and || evaluate to true if either operand is true. They evaluate their second operand only if the first is false. As with and, the only difference between or and || is their precedence. – Just to make life interesting, and and or have the same precedence, and && has a higher precedence than ||. !, not not and ! return the opposite of their operand (false if the operand is true, and true if the operand is false). And, yes, not and ! differ only in precedence. | or false or nil #-->nil nil or false #-->false 99 or false #-->99
A common Ruby idiom makes use of this.
puts ( ((myhash ||= {})['key'] ||= []) << 'arrEl_1' << 'arrEl_2' )[1] #->arrEl_2
|
defined? Returns nil if its argument (which can be an arbitrary expression) is not defined; otherwise it returns a description of that argument. If the argument is yield, defined? returns the string "yield" if a code block is associated with the current context. | defined? defined? 1 #-->"expression" defined? dummy #-->nil defined? printf #-->"method" defined? String #-->"constant" defined? $_ #-->"globalvariable" defined? Math::PI #-->"constant" defined? a = 1 #-->"assignment" defined? 42.abs #-->"method" |
About Is a variable an object? In Ruby, the answer is “no.” A variable is simply a reference to an object. Objects float around in a big pool somewhere (the heap, most of the time) and are pointed to by variables. Naming rules Name can be any combination of letters, digits, and underscores (with the proviso that the character following an @ sign may not be a digit). However, by convention multiword instances variables are written with underscores between the words, and multiword class names are written in MixedCase (with each word capitalized). | |
variable reference person1 = "Tim" person2 = person1 person1[0] = 'J' person1 #-->"Jim" person2 #-->"Jim" |
|
localVar, _localVar Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore. | Local variables vname _27 varName var_name variable7 Local variable person = "Tim" person.id #-->936870 person.class #-->String person #-->"Tim" |
@instanceVar Instance variable | Instance variables @_ @V @v_name |
$globalVar Global variable | Global variable samples $Global $debug $CUSTOMER $_ $plan9 |
@@classVar Class variable. Unlike global and instance variables, class variables must be initialized before they are used. | Class variables @@varname @@V @@TO_ALL @@v_name |
ClassName, ModuleName, ConstName
Class names, module names, and constants must start with an uppercase letter. | sample PI String MyClass RModule |
about The class Array holds a collection of object -references. Each object reference occupies a position in the array, identified by a non-negative integer index. It’s more efficient to access array elements, but hashes provide more flexibility – Literals of class Array are created by placing a comma-separated series of object references between square brackets. – A trailing comma is ignored. – Arrays of strings can be constructed using a shortcut notation, %w, which extracts space-separated tokens into successive elements of the array. A space can be escaped with a backslash. This is a form of general delimited input. Indexing elements – Ruby array index starts at zero. – Index an array with a non-negative integer, and it returns the object at that position or returns nil if nothing is there. Index an array with a negative integer, and it counts from the end. – You can also index arrays with a pair of numbers, [ -start, -count ]. This returns a new array consisting of references to count objects starting at position start. - You can index arrays using ranges, in which start and end positions are separated by two or three periods. The -two-period form includes the end position, and the -three-period form does not. remove Modifying elements in array – The [ ] operator has a corresponding [ ]= operator, which lets you set elements in the array. If used with a single integer index, the element at that position is replaced by whatever is on the right side of the assignment. Any gaps that result will be filled with nil. – If the index to [ ]= is two numbers (a start and a length) or a range, then those elements in the original array are replaced by whatever is on the right side of the assignment. If the length is zero, the right side is inserted into the array before the start position; no elements are removed. If the right side is itself an array, its elements are used in the replacement. The array size is automatically adjusted if the index selects a different number of elements than are available on the right side of the assignment. arr.length -> Integer Returns length of array .to_a Converts a range to a list | arrays a = [ 1, 'cat', 3.14 ] # create array with three elements a[0] # --> 1 access the first element a[2] = nil # set the third element a #--> [1, "cat", nil] arr = [ fred, 10, 3.14, "This is a string", barney("pebbles"), ] %w( first sec\ ond ) #-> ["first", "sec ond"] b = Array.new # array constructor b.class #--> Array b.length #-->0 b[0] = "second" b[1] = "array" b #-->["second", "array"] c = [] # array short constructor c.class #--> Array
string to array
a = %w{ ant bee cat dog elk }
a[0] #--> "ant"
a[3] #--> "dog"
array indexation (-1 = the last) a = [ 1, 3, 5, 7, 9 ] a[1] #-->3 a[2] #-->5 a[-1] #-->9 a[99] #-->nil subarray – arr[start, count] a = [ 1, 3, 5, 7, 9 ] a[1, 3] #-->[3, 5, 7] a[3, 1] #-->[7] a[3, 2] #-->[7, 9] subarray – two-period three-period a = [ 1, 3, 5, 7, 9 ] a[1..3] #-->[3, 5, 7] a[1...3] #-->[3, 5] a[3..3] #-->[7] a[3..1] #-->[] set elements in array a = [ 1, 3, 5, 7, 9 ] a[1] = "bat" #-->[1, "bat", 5, 7, 9] a[2] = "cat" #-->[1, "bat", "cat", 7, 9] a[3] = [ 9, 8 ] #-->[1, "bat", "cat", [9, 8], 9] a[6] = 99 #-->[1, "bat", "cat", [9, 8], 9, nil, 99] set ranges elements in array, replacing elements a = [ 1, 3, 5, 7, 9 ] #-->[1, 3, 5, 7, 9] a[2, 2] = ’cat’ #-->[1, 3, "cat", 9] a[2, 0] = ’dog’ #-->[1, 3, "dog", "cat", 9] inserting elements a[1, 1] = [ 9, 8, 7 ] #-->[1, 9, 8, 7, "dog", "cat", 9] a[0..3] = [] #-->["dog", "cat", 9] removing elements a[5..6] = 99, 98 #-->["dog", "cat", 9, nil, nil, 99, 98] ranges to array (1...10).to_a #-->[1, 2, 3, 4, 5, 6, 7, 8, 9] ('bar'..'bat').to_a #-->["bar", "bas", "bat"] |
arr.sort -> Array Returns a new array created by sorting arr. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. arr.sort! -> arr Same as Array.sort, but modifies the receiver in place. arr is effectively frozen while a sort is in progress. | Array sort a = [ "d", "a", "e", "c", "b" ] a.sort #-> ["a", "b", "c", "d", "e"] a.sort {|x,y| y <=> x } #-> ["e", "d", "c", "b", "a"] Array sort! a = [ "d", "a", "e", "c", "b" ] a.sort! #-> ["a", "b", "c", "d", "e"] a #-> ["a", "b", "c", "d", "e"] |
arr.reverse -> Array Returns a new array using arr's elements in reverse order. arr.reverse! -> arr or nil Same as reverse, but returns nil if arr is unchanged (arr.length is zero or one). | reverse ["a", "b", "c"].reverse #->["c", "b", "a"] [1].reverse #->[1] reverse! a = ["a", "b", "c"] a.reverse! #->["c", "b", "a"] a #->["c", "b", "a"] [ 1 ].reverse! #->nil |
reverse_each Same as Array.each, but traverses arr in reverse order. |
reverse_each
a = ["a", "b", "c"]
a.reverse_each {|x| print x, " " }
produces:
c b a
|
arr.clear -> arr Removes all elements from arr. | clear a = ["a", "b", "c", "d", "e"] a.clear #-> [] |
arr.collect {| obj | block } -> Array
Returns a new array by invoking block once for every element, passing each element as a parameter to block. The result of block is used as the given element in the new array. arr.collect! {| obj | block } -> arr
Invokes block once for each element of arr, replacing the element with the value returned by block. |
collect
a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" } #-> ["a!", "b!", "c!", "d!"]
a #-> ["a", "b", "c", "d"]
collect!
a = [ "a", "b", "c", "d" ]
a.collect! {|x| x + "!" } #-> ["a!", "b!", "c!", "d!"]
a #-> ["a!", "b!", "c!", "d!"]
|
about Hashes (sometimes known as associative arrays, maps, or dictionaries) are similar to arrays in that they are indexed collections of object references. However, while you index arrays with integers, you can index a hash with objects of any type: strings, regular expressions, and so on. When you store a value in a hash, you actually supply two objects — the index, normally called the key, and the value. You can subsequently retrieve the value by indexing the hash with the same key. The values in a hash can be objects of any type. a hash by default returns nil when indexed by a key it doesn’t contain. Sometimes you’llwant to change this default. For example, if you’re using a hash to count the number of times each key occurs, it’s convenient to have the default value be zero. This is easily done by specifying a default value when you create a new, empty hash. Compared with arrays, hashes have one significant advantage: they can use any object as an index. However, they also have a significant disadvantage: their elements are not ordered, so you cannot easily use a hash as a stack or a queue. Also thes are not so efficient as arrays. Hash does not support multiple keys with the same value |
hash
inst_section = {
'cello' => 'string',
'clarinet' => 'woodwind',
'drum' => 'percussion',
}
h = {} # ={}
h.length #-->0 =length
h['dog'] #-->nil
hash
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
h.length #-->3 length
h['dog'] #-->"canine"
h['cow'] = 'bovine'
h[12] = 'dodecine'
h['cat'] = 99
h #-->{"cow"=>"bovine", "cat"=>99, 12=>"dodecine",
# "donkey"=>"asinine", "dog"=>"canine"}
|
Hash[ [ key => value ]* ] -> Hash
Creates a new hash populated with the given objects.
– Equivalent to the literal { key, value, ... }.
– Keys and values occur in pairs, so there must be an even number of arguments. | Hash[ Hash["a", 100, "b", 200] #->{"a"=>100, "b"=>200} Hash["a" => 100, "b" => 200] #->{"a"=>100, "b"=>200} { "a" => 100, "b" => 200 } #->{"a"=>100, "b"=>200} |
Hash.new( Object=nil ) -> Hash Returns a new, empty hash. – If Object is specified, it will be used as the default value. |
Hash.new
h = Hash.new("Go Fish")
h["a"] = 100
h["b"] = 200
h["a"] #->100
h["c"] #->"Go Fish"
0 by defaul instead NIL histogram = Hash.new(0) histogram['key1'] --> 0 histogram['key1'] = histogram['key1'] + 1 histogram['key1'] --> 1 |
hsh[ aKeyObject ] -> aValueObject
Element Reference – Retrieves the aValueObject stored for aKeyObject. – If not found, returns the default value. |
Element Reference
h = { "a" => 100, "b" => 200 }
h["a"] #->100
h["c"] #->nil
|
hsh[ aKeyObject ] = aValueObject -> aValueObject Element Assignment – Associates the value given by aValueObject with the key given by aKeyObject. – aKeyObject should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen). |
Element Assignment
h = { "a" => 100, "b" => 200 }
h["a"] = 9
h["c"] = 4
h #->{"a"=>9, "b"=>200, "c"=>4}
|
hsh == anOtherHash -> true or false Equality – Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. |
Equality
h1 = { "a" => 1, "c" => 2 }
h2 = { "a" => 1, "c" => 2, 7 => 35 }
h3 = { "a" => 1, "c" => 2, 7 => 35 }
h4 = { "a" => 1, "d" => 2, "f" => 35 }
h1 == h2 #->false
h2 == h3 #->true
h3 == h4 #->false
|
hsh.default -> Object Returns the "default value" that is, the value returned for a key that does not exist in the hash. – Defaults to nil. hsh.default = Object -> hsh
Sets the "default value" |
default
h = { "a" => 100, "b" => 200 }
h.default = "Go fish"
h.default #->Go fish
h["a"] #->100
h["z"] #->"Go fish"
|
hsh.delete( aKeyObject ) -> aValueObject Deletes and returns a key-value pair from hsh whose key is equal to aKeyObject. – If the key is not found, returns the default value. – If the optional code block is given and the key is not found, pass in the key and return the result of block. |
delete
h = { "a" => 100, "b" => 200 }
h.delete("a") #->100
h.delete("z") #->nil
h.delete("z") { |el| "#{el} not found" } #->"z not found"
|
hsh.delete_if {| key, value | block } -> hsh
Deletes every key-value pair from hsh for which block evaluates to true. |
delete_if
h = { "a" => 100, "b" => 200, "c" => 300 }
h.delete_if {|key, value| key >= "b" } #->{"a"=>100}
|
hsh.sort -> Array Converts hsh to a nested array of [key, value] arrays and sorts it, using Array.sort. |
Hash sort
h = { "a" => 20, "b" => 30, "c" => 10 }
h.sort #-> [["a", 20], ["b", 30], ["c", 10]]
h.sort {|a,b| a[1]<=>b[1]} #-> [["c", 10], ["a", 20], ["b", 30]]
|
hsh.clear -> hsh Removes all key-value pairs from hsh. |
clear
h = {"a" => 100, "b" => 200}
h.clear #-> {}
|
hsh.each {| key, value | block } -> hsh
Calls block once for each key in hsh, passing the key and value as parameters. |
each
h = { "a" => 100, "b" => 200 }
h.each {|key, value| print key, " is ", value, "\n" }
produces:
a is 100
b is 200
|
hsh.each_key {| key | block } -> hsh
Calls block once for each key in hsh, passing the key as a parameter. |
each_key
h = { "a" => 100, "b" => 200 }
h.each_key {|key| puts key }
produces:
a
b
|
hsh.each_value {| value | block } -> hsh
Calls block once for each key in hsh, passing the value as a parameter. |
each_value
h = { "a" => 100, "b" => 200 }
h.each_value {|value| puts value }
produces:
100
200
|
hsh.empty? -> true or false Returns true if hsh contains no key-value pairs. |
empty?
{}.empty? #->true
|
hsh.fetch( aKeyObject [, aDefObject ] ) -> Object Returns a value from the hash for the given key. If the key can't be found, there are several options: – With no other arguments, it will raise an IndexError exception; – if aDefObject is given, then that will be returned; – if the optional code block is specified, then that will be run and its result returned. |
fetch
h = { "a" => 100, "b" => 200 }
h.fetch("a") #->100
h.fetch("z", "go fish") #->"go fish"
h.fetch("z") { |el| "go fish, #{el}"} #->"go fish, z"
The following example shows that an exception is raised if the key is not found and a default value is not supplied.
h = { "a" => 100, "b" => 200 }
h.fetch("z")
produces:
prog.rb:2:in `fetch': key not found (IndexError)
from prog.rb:2
|
hsh.has_key?( aKeyObject ) -> true or false Returns true if the given key is present in hsh. |
has_key?
h = { "a" => 100, "b" => 200 }
h.has_key?("a") #->true
h.has_key?("z") #->false
|
hsh.has_value?( aValueObject ) -> true or false Returns true if the given value is present for some key in hsh. |
has_value?
h = { "a" => 100, "b" => 200 }
h.has_value?(100) #->true
h.has_value?(999) #->false
|
hsh.index( aValueObject ) -> aKeyObject Returns the key for a given value. – If not found, returns the default value. |
index
h = { "a" => 100, "b" => 200 }
h.index(200) #->"b"
h.index(999) #->nil
|
hsh.indexes( [ key ]+ ) -> Array Returns a new array consisting of values for the given key(s). – Will insert the default value for keys that are not found. |
indexes
h = { "a" => 100, "b" => 200, "c" => 300 }
h.indexes("a", "c") #->[100, 300]
h.indexes("a", "c", "z") #->[100, 300, nil]
|
hsh.invert -> Hash Returns a new hash created by using hsh's values as keys, and the keys as values. |
invert
h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
h.invert #->{0=>"a", 100=>"n", 200=>"d", 300=>"y"}
|
hsh.keys -> Array Returns a new array populated with the keys from this hash. |
keys
h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
h.keys #->["a", "b", "c", "d"]
|
hsh.values -> Array Returns a new array populated with the values from hsh. |
values
h = { "a" => 100, "b" => 200, "c" => 300 }
h.values #->[100, 200, 300]
|
hsh.length -> Fixnum Returns the number of key-value pairs in the hash. |
length
h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
h.length #->4
h.delete("a") #->200
h.length #->3
|
hsh.rehash -> hsh Rebuilds the hash based on the current hash values for each key. – If values of key objects have changed since they were inserted, this method will reindex hsh. – If Hash.rehash is called while an iterator is traversing the hash, an IndexError will be raised in the iterator. |
rehash
a = [ "a", "b" ]
c = [ "c", "d" ]
h = { a => 100, c => 300 }
h[a] #->100
a[0] = "z"
h[a] #->nil
h.rehash #->{["z", "b"]=>100, ["c", "d"]=>300}
h[a] #->100
|
hsh.reject {| key, value | block } -> Hash
Same as Hash.delete_if, but works on (and returns) a copy of the hsh. – Equivalent to hsh.dup.delete_if hsh.reject! {| key, value | block } -> hsh or nil
Equivalent to Hash.delete_if, but returns nil if no changes were made. | |
hsh.replace( anOtherHash ) -> hsh Replaces the contents of hsh with the contents of anOtherHash. |
replace
h = { "a" => 100, "b" => 200 }
h.replace({ "c" => 300, "d" => 400 }) #->{"c"=>300, "d"=>400}
|
hsh.shift -> Array or nil Removes a key-value pair from hsh and returns it as the two-item array [ key, value ], or nil if the hash is empty. |
shift
h = { 1 => "a", 2 => "b", 3 => "c" }
h.shift #->[1, "a"]
h #->{2=>"b", 3=>"c"}
|
hsh.to_a -> Array Converts hsh to a nested array of [ key, value ] arrays. |
to_a
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
h.to_a #->[["a", 100], ["c", 300], ["d", 400]]
|
hsh.to_s -> String Converts hsh to a string by converting the hash to an array of [ key, value ] pairs and then converting that array to a string using Array.join with the default separator. |
to_s
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
h.to_s #->"a100c300d400"
|
hsh.update( anOtherHash ) -> hsh Adds the contents of anOtherHash to hsh, overwriting entries with duplicate keys with those from anOtherHash. |
update
h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.update(h2) #->{"a"=>100, "b"=>254, "c"=>300}
inline
h1 = {:a => 100, :b => 200}
h1.update(:b => 254, :c => 300) #-> {:b=>254, :c=>300, :a=>100}
|
fflop Ranges as Conditions Ranges may also be used as conditional expressions. Range can be used as a kind of flip-flop, returning true when some event happens and then staying true until a second event occurs. This facility is normally used within loops. Ranges as Intervals Interval test: seeing if some value falls within the interval represented by the range.We do this using ===, the case equality operator. | ranges digits = 0..9 digits.include?(5) #-->true digits.min #-->0 digits.max #-->9 digits.reject {|i| i < 5 } #-->[5, 6, 7, 8, 9] digits.each {|digit| dial(digit) } #-->0..9
|
Block – A block may also return a value to the method. So you can use if yield(param) ... – A Ruby block can be converted into an object of class Proc. These Proc objects can be stored in variables and passed between methods just like any other object. The code in the corresponding block can be executed at any time by sending the Proc object the message call. – Ruby Proc objects remember the context in which they were created: the local variables, the current object and so on. When called, they recreate this context for the duration of their execution, even if that context has gone out of scope. Other languages call proc objects closures. { ... }
For single-line block Iterator First, a block may appear only in the source adjacent to a method call; the block is written starting on the same line as the method call’s last parameter (or the closing parenthesis of the parameter list). Second, the code in the block is not executed at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method. This is where the magic starts. { |param1, param2, ...| ... } Iterator-block with parameters. Can be invoked by yield(param1, param2, ...) | iterator for Fibonacci numbers def fibUpTo(max) n1, n2 = 1, 1 while n1 <= max yield n1 # invoke block with passing value n1, n2 = n2, n1+n2 # and calculate next end end fibUpTo(1000) { |term| print term, " " } produces: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
do For multiline block do |param1, param2, ...| Multiline block with parameters method { ... } Block associated with method can be invoked inside method by yield block_given? Returns true if a block is associated with the current method proc {...}
Converts a block to a Proc object
Shortcut for Proc.new { ... }.call Calls Proc object |
iterator for I/O
f = File.open("testfile")
f.each do |line|
puts line
end
f.close
#produces:
This is line one
This is line two
This is line three
And so on...
lambda sample
def n_times(thing)
return lambda {|n| thing * n }
end
p1 = n_times(23)
p1.call(3) #-->69
p1.call(4) #-->92
p2 = n_times("Hello ")
p2.call(3) #-->"Hello Hello Hello "
Checking number of arguments
nonchecked = Proc.new { |a, b, c| [ a, b, c ] }
checked = lambda { |a, b, c| [ a, b, c ] }
nonchecked.call(1, 2) # => [1, 2, nil]
nonchecked.call(1, 2, 3, 4) # => [1, 2, 3]
checked.call(1, 2) #--> will raise an exeption "wrong number of arguments (2 for 3) (ArgumentError)"
local variables in block
a = [1, 2]
b = 'cat'
a.each {|b| c = b * a[1] }
a #-->[1, 2]
b #-->2 changed
defined?(c) #-->nil not defined
Proc object
def times(n)
return Proc.new { |val| n * val }
end
#The block multiplies the method’s parameter, “n”, by another value,
# which is passed to the block as a parameter. The following code
# shows this in action.
double = times(2)
double.call(4) #--> 8
santa = times("Ho! ")
santa.call(3) #--> "Ho! Ho! Ho! "
# Even though the parameter “n” is out of scope when the double and
# santa objects are called, its value is still available to the closures.
parametrs to yield
def call_block
yield("hello", 99)
end
call_block {|str, num| ... }
yield class File def File.my_open(*args) result = file = File.new(*args) # If there's a block, pass in the file and close # the file when it returns if block_given? result = yield file file.close end return result end end
Passing block throw parameter
songlist = SongList.new
class JukeboxButton < Button
def initialize(label, &action)
super(label)
@action = action
end
def button_pressed
@action.call(self)
end
end
start_button = JukeboxButton.new("Start") { songlist.start }
pause_button = JukeboxButton.new("Pause") { songlist.pause }
|
if | unless ... [then] Unless is a negated form of the if statement. If you lay out your if statements on multiple lines, you can leave off the then keyword. If is an expression, not a statement — it returns a value. if | unless ... : command You can get even terser and use a colon ":" in place of the then. puts "..." if | unless var > 3 Shortcut for if ... ? ... : ... Ruby also supports the C-style conditional expression. | Sample if count > 10 puts "Try again" elsif tries == 3 puts "You lose" else puts "Enter a number" end
if, unless
mon, day, year = $1, $2, $3 if date =~ /(\d\d)-(\d\d)-(\d\d)/
puts "a = #{a}" if debug
print total unless total.zero?
File.foreach("/etc/fstab") do |line|
next if line =~ /^#/ #--># Skip comments
parse(line) unless line =~ /^$/ #--># Don't parse empty lines
end
unless if true then puts 'first' else puts 'second' end unless false |
switch case var You specify a target at the top of the case statement, and each when clause lists one or more comparisons. As with if, case returns the value of the last expression executed, and you can use a then keyword if the expression is on the same line as the condition. Case operates by comparing the target (the expression after the keyword case) with each of the comparison expressions after the when keywords. This test is done using comparison === target. leap = case As with if statements, you can use a colon ":" in place of the then. |
case sample
case input_line
when "debug"
dump_debug_info
dump_symbols
when /p\s+(\w+)/
dump_variable($1)
when "quit", "exit"
exit
else
print "Illegal command: #{input_line}"
end
using case rating = case votes_cast when 0...10 then Rating::SkipThisOne when 10...50 then Rating::CouldDoBetter else Rating::Rave end ":" in place of the then leap = case when year % 400 == 0: true when year % 100 == 0: false else year % 4 == 0 end case with region kind = case year when 1850..1889 then "Blues" when 1890..1909 then "Ragtime" when 1910..1929 then "New Orleans Jazz" when 1930..1939 then "Swing" when 1940..1950 then "Bebop" else "Jazz" end case with pattern case line when /title=(.*)/ puts "Title is #$1" when /track=(.*)/ puts "Track is #$1" when /artist=(.*)/ puts "Artist is #$1" end You can test the class of objects case shape when Square, Rectangle # ... when Circle # ... when Triangle # ... else # ... end |
Scope The while, until, and for loops are built into the language and do not introduce new scope; previously existing locals can be used in the loop, and any new locals created will be available afterward. The blocks used by iterators (such as loop and each) are a little different. Normally, the local variables created in these blocks are not accessible outside the block. However, if at the time the block executes a local variable already exists with the same name as that of a variable in the block, the existing local variable will be used in the block. Its value will therefore be available after the block finishes. Note that the variable need not have been given a value in the outer scope: the Ruby interpreter just needs to have seen it. A couple of suggestions to minimize the problems with local and block variables interfering: • Keep your methods and blocks short. The fewer variables, the smaller the chance that they’ll clobber each other. It’s also easier to eyeball the code and check that you don’t have conflicting names. • Use different naming schemes for local variables and block parameters. For example, you probably don’t want a local variable called “i,” but that might be perfectly acceptable as a block parameter. In reality, this problem doesn’t arise in practice as often as you may think. | Scope in block [ 1, 2, 3 ].each do |x| y = x + 1 end [ x, y ] produces: prog.rb:4: undefined local variable or method `x' for main:Object (NameError) local variable already exists x = nil y = nil [ 1, 2, 3 ].each do |x| y = x + 1 end [ x, y ] #-->[3, 4]
the Ruby interpreter just needs to have seen it
if false
a = 1
end
3.times {|i| a = i }
a #-->2
|
while [is true] The while loop executes its body zero or more times as long as its condition is true. You’ll come across a wrinkle when you use while and until as statement modifiers. If the statement they are modifying is a begin/end block, the code in the block will always execute at least one time, regardless of the value of the boolean expression. ... while [is true] Shortcut until [becomes true] The until loop is the opposite; it executes the body until the condition becomes true. ... until [becomes true] Shortcut | while sample while weight < 100 and num_pallets <= 30 pallet = next_pallet() weight += pallet.weight num_pallets += 1 end
while
file = File.open("ordinal")
while line = file.gets
puts(line) if line =~ /third/ .. line =~ /fifth/
end
#or slightly differently
while file.gets
print if ~/third/ .. ~/fifth/
end
produces:
third
fourth
fifth
while with block print "Hello\n" while false begin print "Goodbye\n" end while false produces: Goodbye until until play_list.duration > 60 play_list.add(song_list.pop) end |
n.times Iterates n times, executing the block inside 3.upto(6) Iterating up and down between two integers .step(from, step) Iteration with step |
samples
5.times { print "*" } #-->*****
3.upto(6) {|i| print i } #-->3456
99.downto(95) {|i| print i, " " } #-->99 98 97 96 95
50.step(80, 5) {|i| print i, " " } #-->50 55 60 65 70 75 80
|
loop do The loop iterator calls the associated block forever The loop control constructs break, redo, and next let you alter the normal flow through a loop or iterator. continue next Skips to the end of the loop, effectively starting the next iteration. /break break Terminates the immediately enclosing loop; control resumes at the statement following the block. Break and next can be given arguments. When used in conventional loops, it probably makes sense only to do this with break (as any value given to next is effectively lost). If a conventional loop doesn’t execute a break, its value is nil. redo Repeats the loop from the start, but without reevaluating the condition or fetching the next element (in an iterator). retry Restarts any kind of iterator loop. Retry will reevaluate any arguments to the iterator before restarting it. | loop sample i=0 loop do i += 1 next if i < 3 print i break if i > 4 end produces: 345 while sample while line = gets next if line =~ /^\s*#/ # skip comments break if line =~ /^END/ # stop at end # substitute stuff in backticks and try again redo if line.gsub!(/`(.*?)`/) { eval($1) } # process line ... end
retry
for i in 1..100
print "Now at #{i}. Restart? "
retry if gets =~ /^y/i
end
retry will reevaluate any arguments to the iterator before restarting it def do_until(cond) break if cond yield retry end i = 0 do_until(i > 10) do print i, " " i += 1 end produces: 0 1 2 3 4 5 6 7 8 9 10 break with argument result = while line = gets break(line) if line =~ /answer/ end process_answer(result) if result |
for i in 1..3 You can use for to iterate over any object that responds to the method each, such as an Array or a Range. When you write so, Ruby translates it into something like songlist.each do |song| song.play end The only difference between the for loop and the each form is the scope of local variables that are defined in the body | for in sample for i in ['fee', 'fi', 'fo', 'fum'] print i, " " end produces: fee fi fo fum for in with region for i in 1..3 print i, " " end produces: 1 2 3
with array
for i in File.open("ordinal").find_all {|line| line =~ /d$/}
print i.chomp, " "
end
produces: second third
As long as your class defines a sensible each method, you can use a for loop to traverseits objects. class Periods def each yield "Classical" yield "Jazz" yield "Rock" end end periods = Periods.new for genre in periods print genre, " " end produces: Classical Jazz Rock |
class ClassName Class definition. First letter of ClassName must be in uppercase class SubClass < ParentClass Class inheritance def instance_method(param, ...) Instance Method def method(arg1="Val1", arg2="Val2", ...)
Default values for a method’s arguments def instance_method(param1, *args) – Gets parameters for transferring – But what if you want to pass in a variable number of arguments or want to capture multiple arguments into a single parameter? Placing an asterisk before the name of the parameter after the “normal” parameters does just that. Parameter is prefixedwith an asterisk, so all the remaining arguments are bundled into a new Array, which is then assigned to that parameter. def method(arg1, &block)
If the last parameter in a method definition is prefixed with an ampersand, any associated block is converted to a Proc object, and that object is assigned to the parameter and can be called by .call() method. class method def ClassName.class_method(param, ...) Class Method. Sometimes a class needs to provide methods that work without being tied to any particular object. – For class and module methods, the receiver will be the class or module name. def initialize(param, ...) Calls for new object initialization when you use Class.new(param) def initialize(label, &action)
If the last parameter in a method definition is prefixed with an ampersand Ruby looks for a code block whenever that method is called. That code block is converted to an object of class Proc and assigned to the parameter. .method!
Method is “dangerous,” or modify the receiver. .method?
Method acts as querie. self If you omit the receiver, it defaults to self, the current object. This defaulting mechanism is how Ruby implements private methods. Class.superclass Returns the superclass hierarchy Class.ancestors Returns the array of inheritance hierarchy: this class, mixins list, suerclass, ... , Object, Kernel super When you invoke super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super. It passes this method the parameters that were passed to the originally invoked method. calling method, parameters, return obj.method – You can omit the parentheses around the argument list when calling a method.2 However, except in the simplest cases we don’t recommend this – some subtle problems can trip you up.3 Our rule is simple: if you have any doubt, use parentheses. – You get a warning if you put a space between a method name and an open parenthesis. – The return value of a method is the value of the last expression executed or the result of an explicit return expression. The value of a return is the value of its argument(s). It is idiomatic Ruby to omit the return if it isn’t needed. – Every called method returns a value (although no rule says you have to use that value). – In particular, you must use parentheses on a method call that is itself a parameter to another method call (unless it is the last parameter). – If you give return multiple parameters, the method returns them in an array. You can use parallel assignment to collect this return value. obj.method("param1", *[param2, param3]) When you call a method, you can explode an array, so that each of its members is taken as a separate parameter. Do this by prefixing the array argument (which must follow all the regular arguments) with an asterisk. hash, parameters obj.method(param, – You can place key => value pairs in an argument list, as long as they follow any normal arguments and precede any array and block arguments. All these pairs will be collected into a single hash and passed as one argument to the method. No braces are needed. – In idiomatic Ruby you’d probably use symbols rather than strings, as symbols make it clearer that you’re referring to the name of something. class ClassName Accessor methods. The construct :artist is an expression that returns a Symbol object corresponding to artist. You can think of :artist as meaning the name of the variable artist, and plain artist as meaning the value of the variable. In this example, we named the accessor methods name, artist, and duration. The corresponding instance variables, @name, @artist, and @duration, will be created automatically. Inheritance, multiple inheritance Ruby offers an interesting and powerful compromise, giving you the simplicity of single inheritance and the power of multiple inheritance. A Ruby class has only one direct parent, so Ruby is a singleinheritance language. However, Ruby classes can include the functionality of any number of mixins (a mixin is like a partial class definition). This provides a controlled multiple-inheritance-like capability with none of the drawbacks. private methods Method protection Ruby gives you three levels of protection. – Public methods can be called by anyone — no access control is enforced. Methods are public by default (except for initialize, which is always private). – Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family. – Private methods cannot be called with an explicit receiver — the receiver is always self. This means that private methods can be called only in the context of the current object; you can’t invoke another object’s private methods. – The difference between “protected” and “private” is fairly subtle and is different in Ruby than in most common OO languages. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object — it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller – Ruby differs from other OO languages in another important way. Access control is determined dynamically, as the program runs, not statically. You will get an access violation only when the code attempts to execute the restricted method. – Private methods may not be called with a receiver, so they must be methods available in the current object. Important – Classes and modules are never closed. You can add to and alter all classes and modules (including those built in to Ruby itself). Just open a class definition for an existing class, and the new contents you specify will be added to whatever’s there. – If you don’t specify a parent when defining a class, Ruby supplies class Object as a default. This means that all objects have Object as an ancestor and that Object’s instance methods are available to every object in Ruby. to_s is one of more than 35 instance methods in class Object. | Class sample class Song MAX_TIME = 5*60 # constant @@plays = 0 # class variable def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def [](index) # def [] invokes by songObj[7] with 7 as parametr @songs[index] end end inheritance class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end end superclass class Base end class Derived < Base end Base.superclass # => Object Derived.superclass # => Base super class KaraokeSong < Song def to_s super + " [#@lyrics]" end end Arguments to array def varargs(arg1, *rest) # *args "Got \#{arg1} and \#{rest.join(', ')}" end varargs("one") #-->"Got one and " varargs("one", "two") #-->"Got one and two" varargs "one", "two", "three" #-->"Got one and two, three" returning def meth_two(arg) case when arg > 0 "positive" when arg < 0 "negative" else "zero" end end meth_two(23) #-->"positive" meth_two(0) #-->"zero" return array def meth_three 100.times do |num| square = num*num return num, square if square > 1000 end end meth_three #-->[32, 1024] num, square = meth_three num #-->32 square #-->1024
passing array
def five(a, b, c, d, e)
"I was passed #{a} #{b} #{c} #{d} #{e}"
end
five(1, 2, 3, 4, 5 ) #-->"I was passed 1 2 3 4 5"
five(1, 2, 3, *['a', 'b']) #-->"I was passed 1 2 3 a b"
five(*(10..14).to_a) #-->"I was passed 10 11 12 13 14"
class method calling
File.size("testfile") #-->66
Math.sin(Math::PI/4) #-->0.707106781186548
self self.class #-->Object self.frozen? #-->false frozen? #-->false self.id #-->967900 id #-->967900 # we could not call the method # class without a receiver. This is because class is also a keyword in Ruby
Passing block
class TaxCalculator
def initialize(name, &block)
@name, @block = name, block
end
def get_tax(amount)
"#@name on #{amount} = #{ @block.call(amount) }"
end
end
tc = TaxCalculator.new("Sales tax") {|amt| amt * 0.075 }
tc.get_tax(100) #-->"Sales tax on 100 = 7.5"
tc.get_tax(250) #-->"Sales tax on 250 = 18.75"
Class sample class Shape def Shape.triangle(side_length) Shape.new(3, side_length*3) end def Shape.square(side_length) Shape.new(4, side_length*4) end end getter/setter class Song def title # attribute getter (reader) @title # returns instance variable end def title=(title) # attribute setter (writer)<B><U></U></B> @title = title end end aSong.title = "Chicago" # aSong.title=("Chicago")
attr_reader attr_writer sample
class Song
attr_reader :name, :artist, :duration
attr_writer :duration
end
song = Song.new("Bicylops", "Fleck", 260)
song.artist #-->"Fleck"
song.name #-->"Bicylops"
song.duration #--> 260
song.duration = 257
song.duration #--> 257
Using Accessors within a Class class BrokenAmplifier attr_accessor :left_channel, :right_channel def volume=(vol) left_channel = self.right_channel = vol end end ba = BrokenAmplifier.new ba.left_channel = ba.right_channel = 99 ba.volume = 5 ba.left_channel #-->99 ba.right_channel #-->5 # We forgot to put “self.” in front of the assignment to left_channel, # so Ruby stored the new value in a local variable of method volume=; # the object’s attribute never got updated. This can be a tricky bug to # track down. virtual attributes class Song def duration_in_minutes @duration/60.0 # force floating point end def duration_in_minutes=(new_duration) @duration = (new_duration*60).to_i end end song = Song.new("Bicylops", "Fleck", 260) song.duration_in_minutes #--> 4.33333333333333 song.duration_in_minutes = 4.2 song.duration #--> 252
Adding functionality with a mixin
module Enumerable
def find
each { |val| return val if yield(val) }
end
end
include class Array include Enumerable end method protection class MyClass def method1 # default is '=public' #... end protected # subsequent methods will be '=protected' def method2 # will be 'protected' #... end private # subsequent methods will be '=private' def method3 # will be 'private' #... end public # subsequent methods will be '=public' def method4 # and this will be 'public' #... end end #or... class MyClass def method1 end # ... and so on public :method1, :method4 #=public protected :method2 #=protected private :method3 #=private end |
module ModuleName – Modules provide a namespace and prevent name clashes. – Modules implement the mixin facility. – Constants and class methods may be placed in a module without worrying about their names conflicting with constants and methods includes include ModuleName – The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. – Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior. – One of the other questions folks ask about mixins is, how is method lookup handled? In particular, what happens if methods with the same name are defined in a class, in that class’s parent class, and in a mixin included into the class? The answer is that Ruby looks first in the immediate class of an object, then in the mixins included into that class, and then in superclasses and their mixins. If a class has multiple modules mixed in, the last one included is searched first. load 'filename.rb' – The load method includes the named Ruby source file every time the method is executed. – Accept relative and absolute paths. If given a relative path (or just a plain name), they’ll search every directory in the current load path ($:) for the file. – Local variables in a loaded or required file are not propagated to the scope that loads or requires them. – Since load will include the source unconditionally, you can use it to reload a source file that may have changed since the program began. – For a less contrived use of this facility, consider a Web application that reloads components while running. This allows it to update itself on the fly; it needn’t be restarted for new version of the software to be integrated. This is one of the many benefits of using a dynamic language such as Ruby. require 'filename' – Loads any given file only once. – Require has additional functionality: it can load shared binary libraries. – Accept relative and absolute paths. If given a relative path (or just a plain name), they’ll search every directory in the current load path ($:) for the file. – Local variables in a loaded or required file are not propagated to the scope that loads or requires them. – What may not be obvious is that require is an executable statement — it may be inside an if statement, or it may include a string that was just built. The search path can be altered at runtime as well. Just add the directory you want to the array $:. | 2 modules with method 'sin' module Trig PI = 3.141592654 def Trig.sin(x) # .. end def Trig.cos(x) # .. end end module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) # ... end end # in some third program require 'trig' require 'moral' y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD)
Mixin include
module Debug
def who_am_i?
"#{self.class.name} (\##{self.id}): #{self.to_s}"
end
end
class Phonograph
include Debug
# ...
end
class EightTrack
include Debug
# ...
end
ph = Phonograph.new("West End Blues")
et = EightTrack.new("Surrealistic Pillow")
ph.who_am_i? #-->"Phonograph (#935520): West End Blues"
et.who_am_i? #-->"EightTrack (#935500): Surrealistic Pillow"
mixin
class Song
include Comparable
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def <=>(other)
self.duration <=> other.duration
end
end
song1 = Song.new("My Way", "Sinatra", 225)
song2 = Song.new("Bicylops", "Fleck", 260)
song1 <=> song2 #-->1
song1 < song2 #-->true
song1 == song1 #-->true
song1 > song2 #-->false
Local variables are not propagated to the scope that loads or requires them #included.rb: a = 1 def b 2 end #include it into another file: a = "cat" b = "dog" require 'included' a #-->"cat" b #-->"dog" b() #-->2
load
5.times do |i|
File.open("temp.rb","w") do |f|
f.puts "module Temp"
f.puts " def Temp.var"
f.puts " #{i}"
f.puts " end"
f.puts "end"
end
load "temp.rb"
puts Temp.var
end
produces:
0
1
2
3
4
|
:: class Module @@docs = Hash.new(nil) def doc(str) @@docs[self.name] = str end def Module::doc(aClass) # If we're passed a class or module, convert to string # ('<=' for classes checks for same class or subtype) aClass = aClass.name if aClass.type <= Module @@docs[aClass] || "No documentation for #{aClass}" end end class Example doc "This is a sample documentation string" # .. rest of class end module Another doc <<-edoc And this is a documentation string in a module edoc # rest of module end puts Module::doc(Example) puts Module::doc("Another") produces: This is a sample documentation string And this is a documentation string in a module |
|
extend_object(Object) -> Object Extends the specified object by adding this module's constants and methods (which are added as singleton methods). This is the callback method used by Object.extend. | extend_object module Picky def Picky.extend_object(o) if String === o print "Can't add Picky to a String\n" else print "Picky added to ", o.type, "\n" super end end end (s = Array.new).extend Picky # Call Object.extend (s = "quick brown fox").extend Picky produces: Picky added to Array Can't add Picky to a String |
obj.inspect Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string. obj.to_s Returns a string containing a representation of object. For array returns arr.join. For fixnum – decimal representation. For float – as well as a fixed or exponential form of the number, the call may return "NaN"', "Infinity", and "-Infinity". obj.hash Returns the internal hash key used by Hash. |
inspect
test = Song.new('name', 'artist', 'dur')
puts test.inspect
produces:
<Song:0x28bdccc @artist="artist", @duration="dur", @name="name">
inspect samples 1.inspect # => "1" (0.3).inspect # => "0.3" :Hello.inspect # => ":Hello" [ 1, 2, 3 ].inspect # => "[1, 2, 3]" { :first => 1 }.inspect # => "{:first=>1}" File.open(’_vimrc’, ’r’).inspect # => "#<File:_vimrc>" to_s puts test.to_s #-->#<Song:0x28bdc40> class Song def to_s "Song: #@name--#@rtist (#@duration)" end end song = Song.new("Bicylops", "Fleck", 260) song.to_s #--> "Song: Bicylops--Fleck (260)" |
obj.dup -> Object Makes duplicate object and returns the reference. Produces a shallow copy of obj – the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance. | dup person1 = "Tim" person2 = person1.dup person1[0] = 'J' person1 #-->"Jim" person2 #-->"Tim" |
obj.freeze -> obj Prevents further modifications to obj. A TypeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. | freeze a = [ "a", "b", "c" ] a.freeze a << "z" produces: prog.rb:3:in '<<': can't modify frozen array (TypeError) from prog.rb:3 freeze person1 = "Tim" person2 = person1 person1.freeze # prevent modifications to the object person2[0] = "J" produces: prog.rb:4:in `[]=': can't modify frozen string (TypeError) from prog.rb:4 |
obj.frozen? -> true or false Returns the freeze status of obj. | frozen? a = [ "a", "b", "c" ] a.freeze #-> ["a", "b", "c"] a.frozen? #-> true |
obj.extend([Module]+) -> obj Adds to obj the instance methods from each module given as a parameter. | extend module Mod def hello "Hello from Mod.\n" end end class Klass def hello "Hello from Klass.\n" end end k = Klass.new k.hello #-> "Hello from Klass.\n" k.extend(Mod) #-> #<Klass:0x401b598c> k.hello #-> "Hello from Mod.\n" extend module Humor def tickle "hee, hee!" end end a = "Grouchy" a.extend Humor a.tickle #-> "hee, hee!" There is an interesting trick with extend. If you use it within a class definition, the module's methods become class methods. module Humor def tickle "hee, hee!" end end class Grouchy include Humor extend Humor end Grouchy.tickle #-> "hee, hee!" a = Grouchy.new a.tickle #-> "hee, hee!" |
obj.send( Symbol [, args ]* ) -> Object Invokes the method identified by Symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj. |
send
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #-> "Hello gentle readers"
|
num.abs Returns the absolute value of num. | abs -7.abs #--> 7 111.abs #--> 111 |
num.integer? -> true or false Returns true if num is an Integer (including Fixnum and Bignum). | |
bigint, long, short About integer – Integers can be any length (up to a maximum determined by the amount of free memory on your system). – Integers within a certain range (normally -2^30 to 2^30-1 or -2^62 to 2^62-1) are held internally in binary form and are objects of class Fixnum. – Integers outside this range are stored in objects of class Bignum (currently implemented as a variable-length set of short integers). This process is transparent, and Ruby automatically manages the conversion back and forth. – You write integers using an optional leading sign, an optional base indicator (0 for octal, 0d for decimal [the default], 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string (some folks use them in place of commas in larger numbers). – Control characters can be generated using ?\C-x and ?\c-x (the control version of x is x & 0x9f). Metacharacters (x | 0x80) can be generated using ?\M-x. The combination of meta and control is generated using and ?\M-\C-x. You can get the integer value of a backslash character using the sequence ?\\. – A numeric literal with a decimal point and/or an exponent is turned into a Float object, corresponding to the native architecture's double data type. You must both precede and follow the decimal point with a digit (if you write 1.0e3 as 1.e3, Ruby will try to invoke the method e3 in class Fixnum). – Strings that contain just digits are not automatically converted into numbers when used in expressions. |
Integer
num = 81
6.times do
puts "#{num.class}: #{num}"
num *= num
end
produces:
Fixnum: 81
Fixnum: 6561
Fixnum: 43046721
Bignum: 1853020188851841
Bignum: 3433683820292512484657849089281
Bignum: 11790184577738583171520872861412518665678211592275841109096961
Types 123456 => 123456 # Fixnum 0d123456 => 123456 # Fixnum 123_456 => 123456 # Fixnum (underscore ignored) -543 => -543 # Fixnum (negative number) 0xaabb => 43707 # Fixnum (hexadecimal) 0377 => 255 # Fixnum (octal) -0b10_1010 => 42 # Fixnum binary (negated) 123_456_789_123_456_789 => 123456789123456789 # Bignum Characters ?a => 97 # ASCII character ?\n => 10 # code for a newline (0x0a) ?\C-a => 1 # control a = ?A & 0x9f = 0x01 ?\M-a => 225 # meta sets bit 7 ?\M-\C-a => 129 # meta and control a ?\C-? => 127 # delete character |
int.integer? -> true Always returns true. | |
++ int.next -> Integer Equal to int + 1. | next 1.next #-> 2 (-1).next #-> 0 |
int.chr -> String Returns a string containing the ASCII character represented by the receiver's value. | chr 65.chr #-> "A" ?a.chr #-> "a" 230.chr #-> "\346" |
flt.ceil -> Integer Returns the smallest Integer greater than or equal to flt. flt.floor -> Integer Returns the largest integer less than or equal to flt. | ceil 1.2.ceil #-> 2 2.0.ceil #-> 2 (-1.2).ceil #-> -1 (-2.0).ceil #-> -2 floor 1.2.floor #-> 1 2.0.floor #-> 2 (-1.2).floor #-> -2 (-2.0).floor #-> -2 |
flt.round -> Integer Rounds flt to the nearest integer. | round 1.5.round #-> 2 (-1.5).round #-> -2 Equivalent to: def round return floor(self+0.5) if self > 0.0 return ceil(self-0.5) if self < 0.0 return 0.0 end |
flt.finite? -> true or false Returns true if flt is a valid IEEE floating point number (it is not infinite, and nan? is false). flt.infinite? -> nil, -1, +1 Returns nil, -1, or +1 depending on whether flt is finite, -infinity, or +infinity. | infinite? (0.0).infinite? #-> nil (-1.0/0.0).infinite? #-> -1 (+1.0/0.0).infinite? #-> 1 |
flt.nan? -> true or false Returns true if flt is an invalid IEEE floating point number. | nan? a = -1.0 #-> -1.0 a.nan? #-> false a = Math.log(a) #-> NaN a.nan? #-> true |
flt.to_i -> Integer Returns flt truncated to an Integer. flt.to_s -> String Returns a string containing a representation of self. As well as a fixed or exponential form of the number, the call may return "NaN", "Infinity", and "-Infinity". | |
Substitutions "...#{expr}...#$globalExp...#@classExp...#@@const..."
Double-quoted strings support a boatload more escape sequences.
The most common is probably \n, the newline character.
In addition, you can substitute the value of any Ruby code into a string using the sequence #{expr}.
If the code is just a global variable, a class variable, or an instance variable, you can omit the braces. |
Substitutes
r = 'E'
$glob = 'G'
@inst = 'I'
@@const = 'C'
puts "...#{r}...#{1+2}...#$glob...#@inst...#@@const..."
produces: "...E...3...G...I...C..."
Substitutes
"Seconds/day: #{24*60*60}" #-->Seconds/day: 86400
"#{'Ho! '*3}Merry Christmas!" #-->Ho! Ho! Ho! Merry Christmas!
"This is line #$." #-->This is line 3
puts "now is #{ def the(a)
'the ' + a
end
the('time')
} for all good coders..."
produces:
now is the time for all good coders...
|
quotting, single-quoted %q and %Q Start delimited single- and double-quoted strings (you can think of %q as a thin quote ', and %Q as a thick quote ").
– The character following the q or Q is the delimiter. If it is an opening bracket "[", brace "{", parenthesis "(", or less-than sign "<", the string is read until the matching close symbol is found. Otherwise the string is read until the next occurrence of the same delimiter.
– The delimiter can be any nonalphanumeric or nonmultibyte character. | Quotting %q/general 'singlequoted-string'/ #->general 'singlequoted-string' %Q!general "doublequoted-string"! #->general "doublequoted-string" %Q{Seconds/day: #{24*60*60}} #->Seconds/day: 86400 |
About string Ruby strings are simply sequences of 8-bit bytes. They normally hold printable characters, but that is not a requirement; a string can also hold binary data. Strings are objects of class String. |
using
line = "/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World"
file, length, name, title = line.chomp.split(/\s*\|\s*/)
name.squeeze!(" ") # removing extra spaces
mins, secs = length.scan(/\d+/)
puts "#{name} - #{title} (#{mins.to_i*60+secs.to_i})"
produces:
Louis Armstrong - Wonderful World (178)
|
mixins Comparable: <, <=, ==, >=, >, between? Enumerable: collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a | |
str % arg -> String Format Uses str as a format specification, and returns the result of applying it to arg. – If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted. – See Kernel.sprintf for details of the format string. | using "%05d" % 123 #-> "00123" "%-5s: %08x" % [ "ID", self.id ] #-> "ID : 200e1670" |
str * Integer -> String Copy Returns a new String containing Integer copies of the receiver. | sample "Ho! " * 3 #-> "Ho! Ho! Ho! " |
str + String -> NewString Concatenation Returns a new String containing String concatenated to str. | sample "Hello from " + self.to_s #-> "Hello from main" |
str << Fixnum -> str Append Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation. | sample a = "hello " a << "world" #-> "hello world" a << 33 #-> "hello world!" a #-> "hello world!" |
str <=> String -> -1, 0, +1 Comparison Returns -1 if str is less than, 0 if str is equal to, and +1 if str is greater than String. – If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one. – If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. – If $= is not false, then the comparison is case insensitive. [The locale is ignored when case-insensitive comparisons are performed, so "\"o" will not match "\"O".] – <=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable. | sample "abcdef" <=> "abcde" #-> 1 "abcdef" <=> "abcdef" #-> 0 "abcdef" <=> "abcdefg" #-> -1 "abcdef" <=> "ABCDEF" #-> 1 $= = true "abcdef" <=> "ABCDEF" #-> 0 |
str == Object -> true or false Equality – If Object is not a String, returns false. Otherwise, returns true if str <=> Object returns zero. – The method String.== does not use Comparable.== | |
str =~ Object -> Fixnum or nil Match – If Object is a Regexp or a String, uses it as a pattern to match against str. – Returns the position the match starts, or nil if there is no match. – Otherwise, invokes Object.=~, passing str as an argument. – The default =~ in Object returns false. | sample "cat o' 9 tails" =~ "\\d" #-> 7 "cat o' 9 tails" =~ /\d/ #-> 7 "cat o' 9 tails" =~ 9 #-> false |
[], substring str[Fixnum] -> Fixnum or nil Element Reference – If passed a single Fixnum, returns the code of the character at that position. – If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. – If given a range, a substring containing characters at offsets given by the range is returned. – In all three cases, if an offset is negative, it is counted from the end of str. – Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end. – If a Regexp is supplied, the matching portion of str is returned. – If a String is given, that string is returned if it occurs in str. – In both cases, nil is returned if there is no match. | samples a = "hello there" a[1] #-> 101 a[1,3] #-> "ell" a[1..3] #-> "ell" a[-3,2] #-> "er" a[-4..-2] #-> "her" a[-2..-4] #-> nil a[/th[aeiou]/] #-> "the" a["lo"] #-> "lo" a["bye"] #-> nil |
str[Fixnum] = Fixnum Element Assignment – Replaces some or all of the content of str. – The portion of the string affected is determined using the same criteria as String.[] – If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. – The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment. | samples a = "hello"; a[2] = 96; a #-> "he`lo" a = "hello"; a[2, 4] = "xyz"; a #-> "hexyz" a = "hello"; a[-4, 2] = "xyz"; a #-> "hxyzlo" a = "hello"; a[2..4] = "xyz"; a #-> "hexyz" a = "hello"; a[-4..-2] = "xyz"; a #-> "hxyzo" a = "hello"; a[/[el]+/] = "xyz"; a #-> "hxyzo" a = "hello"; a["l"] = "xyz"; a #-> "hexyzlo" a = "hello"; a["ll"] = "xyz"; a #-> "hexyzo" a = "hello"; a["bad"] = "xyz"; a #-> "hello" a = "hello"; a[2, 0] = "xyz"; a #-> "hexyzllo" |
str.slice( Fixnum ) -> Fixnum or nil Synonyms for str[] | slice a = "hello there" a.slice(1) #-> 101 a.slice(1,3) #-> "ell" a.slice(1..3) #-> "ell" a.slice(-3,2) #-> "er" a.slice(-4..-2) #-> "her" a.slice(-2..-4) #-> nil a.slice(/th[aeiou]/) #-> "the" a.slice("lo") #-> "lo" a.slice("bye") #-> nil |
str.slice!( Fixnum ) -> Fixnum or nil Deletes the specified portion from str, and returns the portion deleted. – The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment. | slice! string = "this is a string" string.slice!(2) #-> 105 string.slice!(3..6) #-> " is " string.slice!(/s.*t/) #-> "sa st" string.slice!("r") #-> "r" string #-> "thing" |
first uppercase, upper first str.capitalize -> String Returns a copy of str with the first character converted to uppercase and the remainder to lowercase. str.capitalize! -> str or nil Modifies str by converting the first character to uppercase and the remainder to lowercase. – Returns nil if no changes are made. | capitalize "hello".capitalize #-> "Hello" "HELLO".capitalize #-> "Hello" "123ABC".capitalize #-> "123abc" capitalize! a = "hello" a.capitalize! #-> "Hello" a #-> "Hello" a.capitalize! #-> nil |
str.downcase -> String Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. – The operation is locale insensitive – Only characters "A" to "Z" are affected. str.downcase! -> str or nil Downcases the contents of str, returning nil if no changes were made. | downcase "hEllO".downcase #-> "hello" |
str.upcase -> String Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. – The operation is locale insensitive – Only characters "a" to "z" are affected. str.upcase! -> str or nil Upcases the contents of str, returning nil if no changes were made. | upcase "hEllO".upcase #-> "HELLO" |
str.center( Integer ) -> String If Integer is greater than the length of str – returns a new String of length Integer with str centered between spaces – otherwise, returns str. | center "hello".center(4) #-> "hello" "hello".center(20) #-> " hello " |
str.ljust( Integer ) -> String If Integer is greater than the length of str, returns a new String of length Integer with str left justified and space padded; otherwise, returns str. | ljust "hello".ljust(4) #-> "hello" "hello".ljust(20) #-> "hello " |
str.rjust( Integer ) -> String If Integer is greater than the length of str, returns a new String of length Integer with str right justified and space padded; otherwise, returns str. | rjust "hello".rjust(4) #-> "hello" "hello".rjust(20) #-> " hello" |
str.dump -> String Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped. | |
str.crypt( String ) -> String Applies a one-way cryptographic hash to str by invoking the standard library function crypt. – The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./]. | |
~str -> Fixnum or nil Equivalent to $_ =~ str | |
str.index( String [, Offset ] ) -> Fixnum or nil Returns the index of the first occurrence of the given substring, character, or pattern in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search. |
index
"Ruby".index("Ru") #-> 0
"Ruby".index("r") #-> nil
"Ruby".index(117) #-> 1
"Ruby".index("b") #-> 2
"Ruby".index(/.$/, 3) #-> 3
"Ruby".index(/.$/, 4) #-> nil
|
str.rindex( String [, Fixnum ] ) -> Fixnum or nil Returns the index of the last occurrence of the given substring, character, or pattern in str. – Returns nil if not found. – If the second parameter is present, it specifies the position in the string to end the search characters beyond this point will not be considered. |
rindex
"hello".rindex('e') #-> 1
"hello".rindex('l') #-> 3
"hello".rindex('a') #-> nil
"hello".rindex(101) #-> 1
"hello".rindex(/[aeiou]/, -2) #-> 1
|
str.split( pattern=$;, [ limit ] ) -> Array Divides str into substrings based on a delimiter, returning an array of these substrings. – If pattern is a String, then its contents are used as the delimiter when splitting str. – If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored. – If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. – If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if '[visible space]' were specified. – If the limit parameter is omitted, trailing null fields are supressed. – If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). – If negative, there is no limit to the number of fields returned, and trailing null fields are not supressed. | split " now's the time".split #-> ["now's", "the", "time"] " now's the time".split(' ') #-> ["now's", "the", "time"] " now's the time".split(/ /) #-> ["", "now's", "", "the", "time"] "1, 2.34,56, 7".split(/,\s*/) #-> ["1", "2.34", "56", "7"] "hello".split(//) #-> ["h", "e", "l", "l", "o"] "hello".split(//, 3) #-> ["h", "e", "llo"] "hi mom".split(/\s*/) #-> ["h", "i", "m", "o", "m"] "mellow yellow".split("ello") #-> ["m", "w y", "w"] "1,2,,3,4,,".split(',') #-> ["1", "2", "", "3", "4"] "1,2,,3,4,,".split(',', 4) #-> ["1", "2", "", "3,4,,"] "1,2,,3,4,,".split(',', -4) #-> ["1", "2", "", "3", "4", "", ""] |
str.strip Returns a copy of str with leading and trailing whitespace removed. str.strip! -> str or nil Removes leading and trailing whitespace from str. Returns nil if str was not altered. | strip " hello ".strip #-> "hello" "\tgoodbye\r\n".strip #-> "goodbye" " first second third \n ".strip #-> "first second third" |
str.reverse -> String Returns a new string with the characters from str in reverse order. "reverse!" reverses str in place. | reverse puts "abc".reverse #-> cba reverse! s = "abc" s.reverse! puts s |
integer, string to integer str.to_i -> Integer Returns the result of interpreting leading characters in str as a decimal integer. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. The method never raises an exception. | to_i "12345".to_i #-> 12345 "99 red balloons".to_i #-> 99 "0x0a".to_i #-> 0 "hello".to_i #-> 0 |
str.chomp( String=$/ ) -> String Returns a new String with the given record separator removed from the end of str (if present). str.chomp!( String=$/ ) -> str or nil Modifies str in place as described for String.chomp, returning str, or nil if no modifications were made. | chomp "hello".chomp #-> "hello" "hello\n".chomp #-> "hello" "hello \n there".chomp #-> "hello \n there" "hello".chomp("llo") #-> "he" |
str.chop -> String Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String.chomp is often a safer alternative, as it leaves the string unchanged if it doesn't end in a record separator. str.chop! -> str or nil Processes str as for String.chop, returning str, or nil if str is the empty string. | chop "string\r\n".chop #-> "string" "string\n\r".chop #-> "string\n" "string\n".chop #-> "string" "string".chop #-> "strin" "x".chop.chop #-> "" chop! s = "string" #-> string s.chop! #-> strin s #-> strin t = "" t.chop! #-> nil |
str.count( [ String ]+ ) -> Fixnum Each String parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any String that starts with a caret (^) is negated. The sequence c1-c2 means all characters between c1 and c2. |
count
a = "hello world"
a.count("lo") #-> 5 #counts [lo]: he(l)(l)(o) w(o)r(l)d
a.count("lo", "o") #-> 2 #counts intersection [o]: hell(o) w(o)rld
a.count("we", "w", "e") #-> 0 #nothing to count, intersection in null
a.count("rrr", "reee", "r") #-> 1 #counts intersection [r]: hello wo(r)ld
a.count("hello", "^l") #-> 4 #counts intersection [heo]: (h)(e)ll(o) w(o)rld
a.count("ej-m") #-> 4 #counts [ejklm]: h(e)(l)(l)o wor(l)d
|
str.delete( [ String ]+ ) -> String Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String.count str.delete!( [ String ]+ ) -> str or nil Performs a delete operation in place, returning str, or nil if str was not modified. |
delete
"hello".delete("l","lo") #-> "heo"
"hello".delete("lo") #-> "he"
"hello".delete("aeioul", "^l") #-> "hll"
"hello".delete("ej-m") #-> "ho"
"wer'3'33".delete("'") #-> 'wer333'
|
str.each( String=$/ ) {| substr | block } -> str
Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. – If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together. |
each
print "Example one\n"
"hello\nworld".each {|s| p s}
print "Example two\n"
"hello\nworld".each('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each(") {|s| p s}
produces:
Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"
|
str.each_byte {| Fixnum | block } -> str
Passes each byte in str to the given block. |
each_byte
"hello".each_byte {|c| print c, ' ' }
produces:
104 101 108 108 111
|
'', "" str.empty? -> true or false Returns true if str has a length of zero. | empty? "hello".empty? #-> false "".empty? #-> true |
str.sub( pattern, replacement ) -> String Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. – If the string form of the method is used, special variables such as $& will not be useful, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2 may be used. – In the block form, the current match is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call. str.sub!( pattern, replacement ) -> str or nil Performs the substitutions of String.sub in place, returning str, or nil if no substitutions were performed. | sub "hello".sub(/[aeiou]/, '*') #-> "h*llo" "hello".sub(/([aeiou])/, '<\1>') #-> "h<e>llo" "hello".sub('.') {|s| s[0].to_s + ' ' } #-> "104 ello" |
str.gsub( pattern, replacement ) -> String Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block. – If a string is used as the replacement, special variables from the match (such as $& and $1) cannot be substituted into it, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, and so on may be used to interpolate successive groups in the match. – In the block form, the current match is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. – The value returned by the block will be substituted for the match on each call. – The result inherits any tainting in the original string or any supplied replacement string. str.gsub!( pattern, replacement ) -> str or nil Performs the substitutions of String.gsub in place, returning str, or nil if no substitutions were performed. | gsub "hello".gsub(/[aeiou]/, '*') #-> "h*ll*" "hello".gsub(/([aeiou])/, '<\1>') #-> "h<e>ll<o>" "hello".gsub('.') {|s| s[0].to_s + ' '} #-> "104 101 108 108 111 " |
/hex str.hex -> Integer Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. – Zero is returned on error. | hex "0x0a".hex #-> 10 "-1234".hex #-> -4660 "0".hex #-> 0 "wombat".hex #-> 0 |
str.oct -> Integer Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. – Returns 0 if the conversion fails. | oct "123".oct #-> 83 "-377".oct #-> -255 "bad".oct #-> 0 "0377bad".oct #-> 255 |
str.include? String -> true or false Returns true if str contains the given string or character. | include? "hello".include? "lo" #-> true "hello".include? "ol" #-> false "hello".include? ?h #-> true |
str.intern -> Symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. | intern "Koala".intern #-> :Koala |
str.length -> Integer Returns the length of str. | |
str.replace( String ) -> str Replaces the contents and taintedness of str with the corresponding values in String. | replace s = "hello" #-> "hello" s.replace "world" #-> "world" |
str.scan( pattern ) -> Array Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. – If the pattern contains no groups, each individual result consists of the matched string, $&. – If the pattern contains groups, each individual result is itself an array containing one entry per group. | scan a = "cruel world" a.scan(/\w+/) #-> ["cruel", "world"] a.scan(/.../) #-> ["cru", "el ", "wor"] a.scan(/(...)/) #-> [["cru"], ["el "], ["wor"]] a.scan(/(..)(..)/) #-> [["cr", "ue"], ["l ", "wo"]] And the block form: a.scan(/\w+/) {|w| print "<<#{w}>> " } print "\n" a.scan(/(.)(.)/) {|a,b| print b, a } print "\n" produces: <<cruel>> <<world>> rceu lowlr |
str.squeeze( [ String ]* ) -> NewString Builds a set of characters from the String parameter(s) using the procedure described for String.count. – Returns a new string where runs of the same character that occur in this set are replaced by a single character. – If no arguments are given, all runs of identical characters are replaced by a single character. str.squeeze!( [ String ]* ) -> str or nil Squeezes str in place, returning either str, or nil if no changes were made. | squeeze "yellow moon".squeeze #-> "yelow mon" " now is the".squeeze(" ") #-> " now is the" "putters shoot balls".squeeze("m-z") #-> "puters shot balls" |
str.succ -> String Returns the successor to str. – The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence. – If the increment generates a "carry," the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary. str.succ! -> str Equivalent to String.succ , but modifies the receiver in place. | succ "abcd".succ #-> "abce" "THX1138".succ #-> "THX1139" "<<koala>>".succ #-> "<<koalb>>" "1999zzz".succ #-> "2000aaa" "ZZZ9999".succ #-> "AAAA0000" "***".succ #-> "**+" |
str.sum( Fixnum=16 ) -> Integer Returns a basic n-bit checksum of the characters in str, where n is the optional parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2^n - 1. – This is not a particularly good checksum. | |
swap case str.swapcase -> String Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. str.swapcase! -> str or nil Equivalent to String.swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. | swapcase "Hello".swapcase #-> "hELLO" "cYbEr_PuNk11".swapcase #-> "CyBeR_pUnK11" |
str.to_f -> Float Returns the result of interpreting leading characters in str as a floating point number. – Extraneous characters past the end of a valid number are ignored. – If there is not a valid number at the start of str, 0.0 is returned. – The method never raises an exception. | to_f "123.45e1".to_f #-> 1234.5 "45.67 degrees".to_f #-> 45.67 "thx1138".to_f #-> 0.0 |
str.to_s -> str Returns the receiver. | |
str.to_str -> str Synonym for String.to_s. to_str is used by methods such as String#concat to convert their arguments to a string. – Unlike to_s, which is supported by almost all classes, to_str is normally implemented only by those classes that act like strings. Of the built-in classes, only Exception and String implement to_str. | |
transliteration str.tr( fromString, toString ) -> String Returns a copy of str with the characters in fromString replaced by the corresponding characters in toString. – If toString is shorter than fromString, it is padded with its last character. – Both strings may use the c1-c2 notation to denote ranges of characters, and fromString may start with a ^, which denotes all characters except those listed. str.tr!( fromString, toString ) -> str or nil Translates str in place, using the same rules as String.tr. – Returns str, or nil if no changes were made. |
tr
"hello".tr('aeiou', '*') #-> "h*ll*"
"hello".tr('^aeiou', '*') #-> "*e**o"
"hello".tr('el', 'ip') #-> "hippo"
"hello".tr('a-y', 'b-z') #-> "ifmmp"
|
str.tr_s( fromString, toString ) -> String Processes a copy of str as described under String.tr, then removes duplicate characters in regions that were affected by the translation. str.tr_s!( fromString, toString ) -> str or nil Performs String.tr_s processing on str in place, returning str, or nil if no changes were made. |
tr_s
"hello".tr_s('l', 'r') #-> "hero"
"hello".tr_s('el', '*') #-> "h*o"
"hello".tr_s('el', 'hx') #-> "hhxo"
|
str.unpack( format ) -> Array Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted.
– The format string consists of a sequence of single-character directives.
– Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk ("*") will use up all remaining elements.
– The directives sSiIlL may each be followed by an underscore ("_") to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string.
– See also Array.pack.
A String with trailing nulls and spaces removed. -> String
a String. -> String
B Extract bits from each character (msb first) -> String
b Extract bits from each character (lsb first) -> String
C Extract a character as an unsigned integer -> Fixnum
c Extract a character as an integer -> Fixnum
d Treat sizeof(double) characters as a native double -> Float
E Treat sizeof(double) characters as a double in little-endian byte order -> Float
e Treat sizeof(float) characters as a float in little-endian byte order -> Float
f Treat sizeof(float) characters as a native float -> Float
G Treat sizeof(double) characters as a double in network byte order -> Float
g Treat sizeof(float) characters as a float in network byte order -> Float
H Extract hex nibbles from each character (most significant first) -> String
h Extract hex nibbles from each character (least significant first) -> String
I Treat sizeof(int)[1] successive characters as an unsigned native integer -> Integer
i Treat sizeof(int)[1] successive characters as a signed native integer -> Integer
L Treat four[1] successive characters as an unsigned native long integer -> Integer
l Treat four[1] successive characters as a signed native long integer -> Integer
M Extract a quoted-printable string -> String
m Extract a base64 encoded string -> String
N Treat four characters as an unsigned long in network byte order -> Fixnum
n Treat two characters as an unsigned short in network byte order -> Fixnum
P Treat sizeof(char *) characters as a pointer, and return len characters from the referenced location -> String
p Treat sizeof(char *) characters as a pointer to a null-terminated string -> String
S Treat two[1] successive characters as an unsigned short in native byte order -> Fixnum
s Treat two[1] successive characters as a signed short in native byte order -> Fixnum
U Extract UTF-8 characters as unsigned integers -> Integer
u Extract a UU-encoded string -> String
V Treat four characters as an unsigned long in little-endian byte order -> Fixnum
v Treat two characters as an unsigned short in little-endian byte order -> Fixnum
X Skip backward one character
x Skip forward one character
Z String with trailing nulls removed -> String
@ Skip to the offset given by the length argument
[1] – May be modified by appending "_" to the directive. |
unpack
"abc \0\0abc \0\0".unpack('A6Z6') #-> ["abc", "abc "]
"abc \0\0".unpack('a3a3') #-> ["abc", " \000\000"]
"aa".unpack('b8B8') #-> ["10000110", "01100001"]
"aaa".unpack('h2H2c') #-> ["16", "61", 97]
"\xfe\xff\xfe\xff".unpack('sS') #-> [-2, 65534]
"now=20is".unpack('M*') #-> ["now is"]
"whole".unpack('xax2X2X1X2a') #-> ["h", "e", "l", "l", "o"]
Cyrillic unpack
"\320\240\320\270".to_a.pack('A*') --> 'Ри'
|
str.upto( String ) {| s | block } -> str
Iterates through successive values, starting at str and ending at String inclusive, passing each value in turn to the block. – The String.succ method is used to generate each value. |
upto
"a8".upto("b6") {|s| print s, ' ' }
for s in "a8".."b6"
print s, ' '
end
produces:
a8 a9 b0 b1 b2 b3 b4 b5 b6
a8 a9 b0 b1 b2 b3 b4 b5 b6
|
Time.new -> Time Returns a Time object initialized to the current system time. Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds. | new a = Time.new #-> Sun Jun 09 00:19:20 CDT 2002 b = Time.new #-> Sun Jun 09 00:19:20 CDT 2002 a == b #-> false "%.6f" % a.to_f #-> "1023599960.526217" "%.6f" % b.to_f #-> "1023599960.526838" |
Time.at( Time ) -> Time Creates a new time object with the value given by Time, or the given number of seconds (and optional microseconds) from epoch. | at Time.at(0) #-> Thu Jan 01 02:00:00 +0200 1970 Time.at(946702800) #-> Sat Jan 01 07:00:00 +0200 2000 |
Time.gm( year [, month, day, hour, min, sec, usec] ) -> Time Creates a time based on given values, interpreted as UTC (GMT). The year must be specified. Other values default to the minimum value for that field (and may be nil or omitted). Months may be specified by numbers from 1 to 12, or by the three-letter English month names. Hours are specified on a 24-hour clock (0..23). Raises an ArgumentError if any values are out of range. Will also accept ten arguments in the order output by Time.to_a. | gm Time.gm(2000,"jan",1,20,15,1) #-> Sat Jan 01 20:15:01 UTC 2000 |
localtime, timelocal Time.local( year [, month, day, hour, min, sec, usec] ) -> Time Same as Time.gm, but interprets the values in the local time zone. | local Time.local(2000,"jan",1,20,15,1) #-> Sat Jan 01 20:15:01 CST 2000 |
Process.times -> StructTms Returns a Tms structure that contains user and system CPU times for this process. | times t = Process.times puts [ t.utime, t.stime ] #-> [0.375, 0.218] |
time + Numeric -> Time Addition. Adds some number of seconds (possibly fractional) to time and returns that value as a new time. time - Time -> Float Difference. Returns a new time that represents the difference between two times, or subtracts the given number of seconds in Numeric from time. time <=> OtherTime -> -1, 0, +1 Comparison. Compares time with OtherTime or with Numeric, which is the number of seconds (possibly fractional) since epoch. | Addition t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t + (60 * 60 * 24) #-> Mon Nov 26 23:50:41 CST 2001 Difference t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t2 = t + 2592000 #-> Tue Dec 25 23:50:41 CST 2001 t2 - t #-> 2592000.0 t2 - 2592000 #-> Sun Nov 25 23:50:41 CST 2001 Comparison t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t2 = t + 2592000 #-> Tue Dec 25 23:50:41 CST 2001 t <=> t2 #-> -1 t2 <=> t #-> 1 t <=> t #-> 0 |
time.asctime -> String Returns a canonical string representation of time. | asctime Time.now.asctime #-> "Sun Nov 25 23:50:41 2001" |
time.gmtime -> time Converts time to UTC (GMT), modifying the receiver. time.gmt? -> true or false Returns true if time represents a time in UTC (GMT). | gmtime t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.gmt? #-> false t.gmtime #-> Mon Nov 26 05:50:41 UTC 2001 t.gmt? #-> true utc t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.utc? #-> false t.utc #-> Mon Nov 26 05:50:41 UTC 2001 t.utc? #-> true gmt?, utc? t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.gmt? #-> false t.utc? #-> false t = Time.gm(2000,"jan",1,20,15,1) #-> Sat Jan 01 20:15:01 UTC 2000 t.gmt? #-> true t.utc? #-> true |
time.sec -> Fixnum Returns the second of the minute (0..60) for time. – Yes, seconds really can range from zero to 60. This allows the system to inject leap seconds every now and then to correct for the fact that years are not really a convenient number of hours long. | sec t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.sec #-> 41 |
time.min -> Fixnum Returns the minute of the hour (0..59) for time. | min t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.min #-> 50 |
time.hour -> Fixnum Returns the hour of the day (0..23) for time. | hour t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.hour #-> 23 |
time.day -> Fixnum Returns the day of the month (1..n) for time. | day t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.day #-> 25 |
time.wday -> Fixnum Returns an integer representing the day of the week, 0..6, with Sunday == 0. | wday t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.wday #-> 0 |
time.mon -> Fixnum Returns the month of the year (1..12) for time. | mon t = Time.now #-> Sat Mar 31 16:26:44 +0300 2007 t.mon #-> 3 |
time.year -> Fixnum Returns the year for time (including the century). | year t = Time.now #-> Sun Nov 25 23:50:42 CST 2001 t.year #-> 2001 |
time.yday -> Fixnum Returns an integer representing the day of the year, 1..366. | yday t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t.yday #-> 329 |
time.zone -> String Returns the name of the time zone used for time. | zone t = Time.gm(2000, "jan", 1, 20, 15, 1) t.zone #-> "GMT" t = Time.local(2000, "jan", 1, 20, 15, 1) t.zone #-> "CST" |
time.isdst -> true or false Returns true if time occurs during Daylight Saving Time in its time zone. | isdst t = Time.local(2000, 7, 1) #-> Sat Jul 01 00:00:00 CDT 2000 t.isdst #-> true t2 = Time.local(2000, 1, 1) #-> Sat Jan 01 00:00:00 CST 2000 t2.isdst #-> false |
time.localtime -> time Converts time to local time (using the local time zone in effect for this process) modifying the receiver. | localtime t = Time.gm(2000, "jan", 1, 20, 15, 1) t.gmt? #-> true t.localtime #-> Sat Jan 01 14:15:01 CST 2000 t.gmt? #-> false |
time.strftime( String ) -> String Formats time according to the directives in the given format string. Any text not listed as a directive will be passed through to the output string. Directives Format Meaning %a – The abbreviated weekday name ("Sun")
%A – The full weekday name ("Sunday")
%b – The abbreviated month name ("Jan")
%B – The full month name ("January")
%c – The preferred local date and time representation
%d – Day of the month (01..31)
%H – Hour of the day, 24-hour clock (00..23)
%I – Hour of the day, 12-hour clock (01..12)
%j – Day of the year (001..366)
%m – Month of the year (01..12)
%M – Minute of the hour (00..59)
%p – Meridian indicator ("AM" or "PM")
%S – Second of the minute (00..60)
%U – Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W – Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
%w – Day of the week (Sunday is 0, 0..6)
%x – Preferred representation for the date alone, no time
%X – Preferred representation for the time alone, no date
%y – Year without a century (00..99)
%Y – Year with century
%Z – Time zone name
%% – Literal "%" character |
strftime
t = Time.now
t.strftime("Printed on %m/%d/%Y") #-> "Printed on 11/25/2001"
t.strftime("at %I:%M%p") #-> "at 11:50PM"
|
time.to_a -> Array Returns a ten-element Array of values for time: {[ sec, min, hour, day, month, year, wday, yday, isdst, zone ]}.
See the individual methods for an explanation of the valid ranges of each value.
The ten elements can be passed directly to Time.utc or Time.local to create a new Time. | to_a now = Time.now #-> Sun Nov 25 23:50:41 CST 2001 t = now.to_a #-> [41, 50, 23, 25, 11, 2001, 0, 329, false, "CST"] |
time.to_f -> Float Returns the value of time as a floating point number of seconds since epoch. | to_f t = Time.now "%10.5f" % t.to_f #-> "1006753841.72788" t.to_i #-> 1006753841 |
time.to_i -> Integer Returns the value of time as an integer number of seconds since epoch. | to_i t = Time.now "%10.5f" % t.to_f #-> "1006753841.76503" t.to_i #-> 1006753841 |
time.usec -> Integer Returns just the number of microseconds for time. | usec t = Time.now #-> Sun Nov 25 23:50:41 CST 2001 "%10.6f" % t.to_f #-> "1006753841.837830" t.usec #-> 837830 |
time.to_s -> String Returns a string representing time. Equivalent to calling Time.strftime with a format string of "%a %b %d %H:%M:%S %Z %Y". | to_s Time.now.to_s #-> "Sun Nov 25 23:50:41 CST 2001" |
2616 Time.now.httpdate -> String Returns a string which represents the time as rfc1123-date of HTTP-date defined by RFC 2616: day-of-week, DD month-name CCYY hh:mm:ss GMT - Result is always UTC (GMT) | httpdate Time.now.httpdate #-> Tue, 08 Jan 2008 07:49:30 GMT |
Abbreviations used describing dates cwday – An ISO 8601 calendar weekday. 1 is Monday, 7 is Sunday. cweek – An ISO 8601 calendar week. Week 1 is the week containing the first Thursday (or equivalently the week that contains January 4th). cwyear – An ISO 8601 calendar-week-based year. May be different from year, as it rolls forward only on a Monday. jd – The Julian day number - the number of days since January 1st, 4713 BCE. mday – The day of the month (1..31). mjd – A modified Julian day number. mon – The month of the year (1..12). sg – The start of the Gregorian correction: Date::ITALY (the default) for 1582, Date::ENGLAND for 1752, or JULIAN, meaning no correction. You may also provide an arbitrary Julian day number for this parameter, in which case the correction will start from this date. wday – The day of the week (0 is Sunday). week – The week number into a year (1..53). yday – The day into the year (1..366). year – A year (1966, 2001, and the like). | |
Date.new( year=-4712, mon=1, mday=1, sg=Date::ITALY) -> aNewDate Returns a Date for the given year, mon, and mday. If mon is negative, it counts back from the end of the year. If mday is negative, it counts back from the end of the month. Date.new1( jd, sg=Date::ITALY) -> aNewDate Creates a Date corresponding to the given Julian day number. Date.new2( year=-4712, yday=1, sg=Date::ITALY) -> aNewDate Returns a Date for the given year and yday. If yday is negative, it counts back from the end of the year. Date.neww( cyear=1582, cweek=41, cwday=5, sg=Date::ITALY) -> aNewDate Returns a Date for the given cyear, cweek, and cwday. If cweek is negative, it counts back from the end of the year. If cwday is negative, it counts back from the end of the week. | Date require 'date' d = Date.new(2000, 3, 31) #-> #<Date: 2451635,2299161> [d.year, d.yday, d.wday] #-> [2000, 91, 5] [d.month, d.mday] #-> [3, 31] [d.cwyear, d.cweek, d.cwday] #-> [2000, 13, 5] [d.jd, d.mjd] #-> [2451635, 51634.5] (d << 1).to_s #-> "2000-02-29" d.succ.to_s #-> "2000-04-01" (d + 100).to_s #-> "2000-07-09" d.leap? #-> true Date.new(2000, 3, -10).to_s #-> "2000-03-22" d1 = Date.new(2000, 13, 7) #-> #<Date: 2451637,2299161> d1.to_s #-> "2000-04-02" [d1.cwday, d1.wday] #-> [7, 0] |
Date.today( sg=Date::ITALY) -> aNewDate Returns a Date for today. | |
Date.exist?( year, mon, mday, sg=Date::ITALY) -> jd Converts a year, mon, and mday into a Julian day number, or nil if the parameters are invalid. Date.exist2?( year, yday, sg=Date::ITALY) -> jd Converts a year and yday into a Julian day number, returning nil on error. Date.existw?( cyear, cweek, cwday, sg=Date::ITALY) -> jd Converts a cyear, cweek, and cwday into a Julian day number. | |
leap year Date.gregorian_leap?( year ) -> true or false If year does not end with "00", returns true if year is divisible by 4, otherwise returns true if year is divisible by 400. leap year Date.julian_leap?( year ) -> true or false Returns true if year is divisible by 4. | |
About The Math module contains module functions for basic trigonometric and transcendental functions. Pi Constants E = 2.718281828 Value of e (base of natural logarithms) PI = 3.141592654 Value of PI | |
Math.sqrt( Numeric ) -> Float Returns the non-negative square root of Numeric. Raises ArgError if Numeric is less than zero. | |
Math.tan( Numeric ) -> Float Returns the tangent of Numeric (expressed in radians). Math.atan2( y, x ) -> Float Computes the arc tangent given y and x. Returns -PI..PI. | |
Math.sin( Numeric ) -> Float Computes the sine of Numeric (expressed in radians). Returns -1..1. Math.cos( Numeric ) -> Float Computes the cosine of Numeric (expressed in radians). Returns -1..1. | |
Math.exp( Numeric ) -> Float Returns e raised to the power of Numeric. Math.frexp( Numeric ) -> Array Returns a two-element array ([Float, Fixnum]) containing the normalized fraction and exponent of Numeric. Math.ldexp( Float, Integer ) -> Float Returns the value of Float*2^Integer. | |
Math.log( Numeric ) -> Float Returns the natural logarithm of Numeric. Math.log10( Numeric ) -> Float Returns the base 10 logarithm of Numeric. | |
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. |
binding
def getBinding(param)
return binding
end
b = getBinding("hello")
eval "param", b #-> "hello"
|
binding() Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created using Kernel.binding, and are made available to the callback of Kernel.set_trace_func. Binding objects have no class-specific methods. |
binding objects can be passed as the second argument of the Kernel.eval method, establishing an environment for the evaluation.
class Demo
def initialize(n)
@secret = n
end
def getBinding
return binding()
end
end
k1 = Demo.new(99)
b1 = k1.getBinding
k2 = Demo.new(-3)
b2 = k2.getBinding
eval("@secret", b1) #-> 99
eval("@secret", b2) #-> -3
eval("@secret") #-> nil
|
$! (Exception) The exception object passed to raise. $@ (Array) The stack backtrace generated by the last exception. | |
$0 (String) – The name of the top-level Ruby program being executed. – Typically this will be the program's filename. On some operating systems, assigning to this variable will change the name of the process reported (for example) by the ps(1) command. | |
args argv $* (Array) – An array of strings containing the command-line options from the invocation of the program. – Options used by the Ruby interpreter will have been removed. – r/o | |
$" (Array) – An array containing the filenames of modules loaded by require – r/o | |
$$ (Fixnum) – The process number of the program being executed – r/o | |
$? (Fixnum) – The exit status of the last child process to terminate – r/o, thread | |
$: (Array) – An array of strings, where each string specifies a directory to be searched for Ruby scripts and binary extensions used by the load and require methods.
– The initial value is the value of the arguments passed via the -I command-line option, followed by an installation-defined standard library location, followed by the current directory (".").
– This variable may be set from within a program to alter the default search path; typically, programs use $: << dir to append dir to the path
– r/o | |
$-a (Object) – True if the -a option is specified on the command line – r/o $DEBUG (Object) – Set to true if the -d command-line option is specified. | |
__FILE__ (String) – The name of the current source file – r/o | |
$F (Array) – The array that receives the split input line if the -a command-line option is used. | |
$FILENAME (String) – The name of the current input file. – Equivalent to $<.filename – r/o | |
$-i (String) – 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. | |
$-K (String) – Sets the multibyte coding system for strings and regular expressions. – Equivalent to the -K command-line option. | |
$-l (Object) – Set to true if the -l option (which enables line-end processing) is present on the command line. – r/o | |
__LINE__ (String) – The current line number in the source file – r/o | |
$-p (Object) – Set to true if the -p option (which puts an implicit while gets ... end loop around your program) is present on the command line. – r/o | |
$SAFE (Fixnum) – The current safe level. – This variable's value may never be reduced by assignment. | |
$VERBOSE (Object) – Set to true if the -v, --version, or -w option is specified on the command line. – Setting this option to true causes the interpreter and some library routines to report additional information. | |
$/ (String) The input record separator (newline by default). This is the value that routines such as Kernel#gets use to determine record boundaries. – If set to nil, gets will read the entire file. | |
$\ (String) The string appended to the output of every call to methods such as Kernel#print and IO#write. – The default value is nil. | |
$, (String) The separator string output between the parameters to methods such as Kernel#print and Array#join. – Defaults to nil, which adds no text. | |
$. (Fixnum) The number of the last line read from the current input file. | |
$; (String) The default separator pattern used by String#split. – May be set from the command line using the -F flag. | |
cmd, stdin $< (Object) An object that provides access to the concatenation of the contents of all the files given as command-line arguments, or $stdin (in the case where there are no arguments). – $< supports methods similar to a File object: binmode, close, closed?, each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno, lineno=, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip, tell, to_a, to_i, to_io, to_s, along with the methods in Enumerable. – The method file returns a File object for the file currently being read. – This may change as $< reads through the files on the command line. | |
defout, stdout $> (IO) The destination of output for Kernel#print and Kernel#printf. – The default value is $stdout. | |
$_ (String) The last line read by Kernel#gets or Kernel#readline. – Many string-related functions in the Kernel module operate on $_ by default. – The variable is local to the current scope. | |
stderr $stderr (IO) The current standard error output. | |
stdin $stdin (IO) The current standard input. | |
stdout $stdout (IO) The current standard output. | |
ARGF (Object) A synonym for $<. ARGV (Array) A synonym for $*. | |
ENV (Object) – A hash-like object containing the program's environment variables. – An instance of class Object, ENV implements the full set of Hash methods. Used to query and set the value of an environment variable, as in ENV["PATH"] and ENV['term']="ansi". | |
true (TrueClass) Singleton instance of class TrueClass – r/o false (FalseClass) Singleton instance of class FalseClass – r/o | |
nil (NilClass) The singleton instance of class NilClass. – The value of uninitialized instance and global variables – r/o | |
self (Object) The receiver (object) of the current method – r/o | |
DATA (IO) If the main program file contains the directive __END__, then the constant DATA will be initialized so that reading from it will return lines following __END__ from the source file. | |
FALSE (FalseClass) Synonym for false. TRUE (TrueClass) Synonym for true. | |
NIL (NilClass) Synonym for nil. | |
RUBY_PLATFORM (String) The identifier of the platform running this program. – This string is in the same form as the platform identifier used by the GNU configure utility (which is not a coincidence). | |
RUBY_RELEASE_DATE (String) The date of this release. | |
RUBY_VERSION (String) The version number of the interpreter. | |
STDERR (IO) The actual standard error stream for the program. – The initial value of $stderr. | |
STDIN (IO) The actual standard input stream for the program. – The initial value of $stdin. | |
STDOUT (IO) The actual standard output stream for the program. – The initial value of $stdout. | |
TOPLEVEL_BINDING (Binding) A Binding object representing the binding at Ruby's top level — the level where programs are initially executed. | |
close, new file = File.new("testfile", "r") You can create a File object that is open for reading, writing, or both, according to the mode string. open, r, rw, w File.open("filename", "r|w|rw") do |file| The method File.open also opens a file. In regular use, it behaves just like File.new. However, if a block is associated with the call, open behaves differently. Instead of returning a new File object, it invokes the block, passing the newly opened File as a parameter. When the block exits, the file is automatically closed. Returns nil |
|
[~]# ruby programWithGets.rb testfile We can also pass in one or more filenames on the command line, in which case gets will read from each in turn. | gets read from file # copy.rb: while line = gets puts line end # testfile This is line one This is line two This is line three # [~]# ruby copy.rb testfile produces: This is line one This is line two This is line three |
file, file.gets, reading .gets Invokes a block with the next 8-bit byte from the IO object .each_line – Each_line calls the block with each line from the file. – You can pass each_line any sequence of characters as a line separator, and it will break up the input accordingly, returning the line ending at the end of each line of data. |
each_line sample
File.open("testfile") do |file|
file.each_line {|line| puts "Got #{line.dump}" }
end
produces:
Got "This is line one\n"
Got "This is line two\n"
Got "This is line three\n"
Got "And so on...\n"
|
each_byte sample
File.open("testfile") do |file|
file.each_byte {|ch| putc ch; print "." }
end
produces:
T.h.i.s. .i.s. .l.i.n.e. .o.n.e.
.T.h.i.s. .i.s. .l.i.n.e. .t.w.o.
.T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e.
.A.n.d. .s.o. .o.n.......
.
|
|
str = IO.read("testfile")
Read into string |
IO.read sample
str = IO.read("testfile")
str.length #-->66
str[0, 30] #-->"This is line one\nThis is line "
|
arr = IO.readlines("testfile")
– Read into an array – Don’t forget that I/O is never certain in an uncertain world — exceptions will be raised on most errors, and you should be ready to rescue them and take appropriate action. IO.foreach("testfile") {|line| puts line }
This method takes the name of an I/O source, opens it for reading, calls the iterator once for every line in the file, and then closes the file automatically. |
IO.readlines sample
arr = IO.readlines("testfile")
arr.length #-->4
arr[0] #-->"This is line one\n"
|
file, writing file.puts Write to file | |
binary data into a string str1 = "\001\002\003" #-->"\001\002\003" str2 = "" str2 << 1 << 2 << 3 #-->"\001\002\003" [ 1, 2, 3 ].pack("c*") #-->"\001\002\003" pack255 = (0..255).to_a.pack("c*") File.open('test.txt', 'w') do |file| file.print pack255 end append an object to an output IO stream endl = "\n" STDOUT << 99 << " red balloons" << endl produces: 99 red balloons
stringio
require 'stringio'
ip = StringIO.new("now is\nthe time\nto learn\nRuby!")
op = StringIO.new("", "w")
ip.each_line do |line|
op.puts line.reverse
end
op.string #-->"\nsi won\n\nemit eht\n\nnrael ot\n!ybuR\n"
|
|
File.size(fileName) -> Integer Returns the size of the file in bytes. |
size
File.size("testfile") #->66
|
Writing UTF-8 file Iconv.iconv('UTF-8', '//IGNORE', data)
Iconv.iconv('UTF-8', 'CP1251', data) |
UTF-8 outFile
require 'iconv'
File.open(overName, 'w') do |fp|
source = $<.read
begin
out = Iconv.iconv('UTF-8', 'UTF-8', source)
rescue
out = Iconv.iconv('UTF-8', 'CP1251', source)
end
fp.puts(out)
end
|
|
|
/print ios.print([Object=$_ ]) -> nil Writes the given object to ios. The stream must be opened for writing. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method. Returns nil. | |
io.puts([Object]) -> nil Writes the given objects to ios as with IO.print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator. p Is shortcut for "puts obj.inspect" |
puts
$stdout.puts("first line", "second line")
puts
puts 777, 'end'
p "p for puts"
produces:
first line
second line
777
end
p for puts
Sample arr = [1, 2, 3] puts arr.inspect #--> [1, 2, 3] p arr #--> [1, 2, 3] |
begin – When an exception is raised, and independent of any subsequent exception handling, Ruby places a reference to the associated Exception object into the global variable $! – You can have multiple rescue clauses in a begin block, and each rescue clause can specify multiple exceptions to catch. – At the end of each rescue clause you can give Ruby the name of a local variable to receive the matched exception. Many people find this more readable than using $! all over the place. – If no rescue clause matches, or if an exception is raised outside a begin/end block, Ruby moves up the stack and looks for an exception handler in the caller, then in the caller’s caller, and so on. raise – Raise with no parameters, which reraises the exception in $!. This is a useful technique, as it allows you to write code that filters exceptions, passing on those you can’t handle to higher levels. – The first form simply reraises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on. – The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack. – The third formuses the first argument to create an exception and then sets the associated message to the second argument and the stack trace to the third argument. Typically the first argument will be either the name of a class in the Exception hierarchy or a reference to an object instance of one of these classes. retry Use the retry statement within a rescue clause to repeat the entire begin/end block. |
Full sample with user error-class
class MyError < Exception
attr :params
def initialize(params)
@params = params
end
end
begin
print 'Input: '
line = gets
raise if line.chomp == 'des'
raise MyError.new({'repeat' => true}), "not Des :)"
if line.chomp != 'Des' && line.chomp != ''
rescue MyError => detail
puts 'Not Des!'
retry if detail.params['repeat']
rescue
puts "it was 'des', game over"
else
puts 'else block'
ensure
puts 'ensure block'
end
rescue and $! op_file = File.open(opfile_name, "w") begin # Exceptions raised by this code will # be caught by the following rescue clause while data = socket.read(512) op_file.write(data) end rescue SystemCallError $stderr.print "IO failed: " + $! op_file.close File.delete(opfile_name) raise end rescue to local variable begin eval string rescue SyntaxError, NameError => boom print "String doesn't compile: " + boom rescue StandardError => bang print "Error running script: " + bang end
raise with parameters
raise
raise "Missing name" if name.nil?
if i >= names.size
raise IndexError, "#{i} >= size (#{names.size})"
end
raise ArgumentError, "Name too big", caller
|
catch 'cachString' do – Catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered. – When Ruby encounters a throw, it zips back up the call stack looking for a catch block with a matching symbol. When it finds it, Ruby unwinds the stack to that point and terminates the block. | skips puts 'arter while' if 'www' was typed catch :myLabel do while line = gets throw :myLabel if line.chomp == 'www' break if line.chomp == '' end puts 'arter while' end puts "end" catch with string catch 'done' do while line = gets throw 'done' unless fields = line.split(/\t/) songlist.add(Song.new(*fields)) end songlist.play end
throw does not have to appear within the static scope of the catch
def prompt_and_get(prompt)
print prompt
res = readline.chomp
throw :quit_requested if res == "!"
res
end
catch :quit_requested do
name = prompt_and_get("Name: ")
age = prompt_and_get("Age: ")
sex = prompt_and_get("Sex: ")
# ..
# process information
end
|
Exception hierarchy Exception fatal (used internally by Ruby) NoMemoryError ScriptError LoadError NotImplementedError SyntaxError SignalException Interrupt StandardError ArgumentError IOError EOFError IndexError LocalJumpError NameError NoMethodError RangeError FloatDomainError RegexpError RuntimeError SecurityError SystemCallError system-dependent exceptions (Errno::xxx) ThreadError TypeError ZeroDivisionError SystemExit SystemStackError | |
//, case sensitivity, pattern, Regexp /pattern/ Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp's options are not propagated). – If options is a Fixnum, it should be one or more of the constants or-ed together Regexp::EXTENDED – Ignore spaces and newlines Regexp::IGNORECASE – Matches are case insensitive Regexp::POSIXLINE – Newlines treated as any other character – Otherwise, if options is not nil, the regexp will be case insensitive. – Regular expressions are objects of type Regexp – The lang parameter enables multibyte support for the regexp: 'n', 'N' = none 'e', 'E' = EUC 's', 'S' = SJIS 'u', 'U' = UTF-8 |
new
r1 = Regexp.new('^a-z+:\\s+\w+') #-> /^a-z+:\s+\w+/
r2 = Regexp.new(r1, true) #-> /^a-z+:\s+\w+/i
r3 = Regexp.new(r2, Regexp::EXTENDED) #-> /^a-z+:\s+\w+/x
Regexp creating
a = Regexp.new('^\s*[az]') #-->/^\s*[az]/
b = /^\s*[az]/ #-->/^\s*[az]/
c = %r{^\s*[az]} #-->/^\s*[az]/
regexp escape
Regexp.escape('we$xcg^456\sdg\s') #-> 'we\$xcg\^456\\sdg\\s'
|
Options A regular expression may include one or more options that modify the way the pattern matches strings. – If you're using literals to create the Regexp object, then the options comprise one or more characters placed immediately after the terminator. – If you're using Regexp.new, the options are constants used as the second parameter of the constructor. /i, case sensitivity /.../i Case Insensitive. The pattern match will ignore the case of letters in the pattern and string. Matches are also case-insensitive if the global variable $= is set. /o /.../o Substitute Once.
Any #{...} substitutions in a particular regular expression literal will be performed just once, the first time it is evaluated. Otherwise, the substitutions will be performed every time the literal generates a Regexp object./m /.../m Multiline Mode. Normally, "." matches any character except a newline. With the /m option, "." matches any character. /x /.../x Extended Mode. Complex regular expressions can be difficult to read. The 'x' option allows you to insert spaces, newlines, and comments in the pattern to make it more readable. | |
Match operators Once you have a regular expression object, you can match it against a string using Regexp.match(string) or the match operators =~ (positive match) and !~ (negative match). The match operators are defined for both String and Regexp objects. At least one operand of the match operator must be a regular expression. – The match operators return the character position at which the match occurred. | String matching name = "Fats Waller" name =~ /a/ #-->1 name != /z/ #-->true /a/ =~ name #-->1 /a/.match(name) #-->MatchData object /z/.match(name) #-->nil m = /l+(.*)/.match(name) m.to_s #-->ller (whole match) m[1] #-->er (same as $1 when using =~) |
$2, $3, $4, $5, $6, $7, $8 Regexp variables $& – receives the part of the string that was matched by the pattern $+ – contents of the highest-numbered group matched in the last successful pattern match. This variable is local to the current scope. $` – receives the part of the string that preceded the match $' – receives the string after the match $= – If set to any value apart from nil or false, all pattern matches will be case insensitive, string comparisons will ignore case, and string hash values will be case insensitive. – The match also sets the thread-global variables $~ and $1 through $9. The variable $~ is a MatchData object that holds everything you may want to know about the match. $1, and so on, hold the values of parts of the match. Patterns – Within a pattern, all characters except: .|()[]{}+\^$*? match themselves. If you want to match one of these special characters literally, precede it with a backslash.
– Regular expression may contain #{...} expression substitutions. |
Regexp variables
def show_regexp(a, re)
if a =~ re
"#{$`}<<#{$&}>>#{$'}"
else
"no match"
end
end
show_regexp('very interesting', /t/) #-->very in<<t>>eresting
show_regexp('Fats Waller', /a/) #-->F<<a>>ts Waller
show_regexp('Fats Waller', /ll/) #-->Fats Wa<<ll>>er
show_regexp('Fats Waller', /z/) #-->no match
$+ "cat" =~ /(c|a)(t|z)/ # $+ will be set to "t" |
Anchors – The patterns ^ and $ match the beginning and end of a line, respectively. – The sequence \A matches the beginning of a string – \z and \Z match the end of a string. (Actually, \Z matches the end of a string unless the string ends with a \n, it which case it matches just before the \n.) – Similarly, the patterns \b and \B match word boundaries and nonword boundaries, respectively.Word characters are letters, numbers, and underscores. |
Anchors
show_regexp("this is\nthe time", /^the/) #-->this is\n<<the>> time
show_regexp("this is\nthe time", /is$/) #-->this <<is>>\nthe time
show_regexp("this is\nthe time", /\Athis/) #--><<this>> is\nthe time
show_regexp("this is\nthe time", /\Athe/) #-->no match
show_regexp("this is\nthe time", /\bis/) #-->this <<is>>\nthe time
show_regexp("this is\nthe time", /\Bis/) #-->th<<is>> is\nthe time
|
Alternation re1 | re2 – Matches either the regular expression that precedes it or the regular expression that follows it. – There’s a trap for the unwary here, as | has a very low precedence. | Alternation sample a = "red ball blue sky" show_regexp(a, /d|e/) #-->r<<e>>d ball blue sky show_regexp(a, /al|lu/) #-->red b<<al>>l blue sky show_regexp(a, /red ball|angry sky/) #--><<red ball>> blue sky |
\1, \2, \3, $1, $2, $3 Grouping (...) – You can use parentheses to group terms within a regular expression. Everything within the group is treated as a single regular expression. – Parentheses also collect the results of pattern matching. Ruby counts opening parentheses, and for each stores the result of the partial match between it and the corresponding closing parenthesis. You can use this partial match both within the rest of the pattern and in your Ruby program. Within the pattern, the sequence \1 refers to the match of the first group, \2 the second group, and so on. – Outside the pattern, the special variables $1, $2, and so on, serve the same purpose. Composition You can combine regexpes together with the string interpolation mechanism. The included regexp will be surrounded by an uncapturing group. |
Grouping
show_regexp('banana', /an*/) #-->b<<an>>ana
show_regexp('banana', /(an)*/) #--><<>>banana
show_regexp('banana', /(an)+/) #-->b<<anan>>a
a = 'red ball blue sky'
show_regexp(a, /blue|red/) #--><<red>> ball blue sky
show_regexp(a, /(blue|red) \w+/) #--><<red ball>> blue sky
show_regexp(a, /(red|blue) \w+/) #--><<red ball>> blue sky
show_regexp(a, /red|blue \w+/) #--><<red>> ball blue sky
show_regexp(a, /red (ball|angry) sky/) #-->no match
a = 'the red angry sky'
show_regexp(a, /red (ball|angry) sky/) #-->the <<red angry sky>>
Grouping
show_regexp('banana', /an*/) #-->b<<an>>ana
show_regexp('banana', /(an)*/) #--><<>>banana
show_regexp('banana', /(an)+/) #-->b<<anan>>a
a = 'red ball blue sky'
show_regexp(a, /blue|red/) #--><<red>> ball blue sky
show_regexp(a, /(blue|red) \w+/) #--><<red ball>> blue sky
show_regexp(a, /(red|blue) \w+/) #--><<red ball>> blue sky
show_regexp(a, /red|blue \w+/) #--><<red>> ball blue sky
show_regexp(a, /red (ball|angry) sky/) #-->no match
a = 'the red angry sky'
show_regexp(a, /red (ball|angry) sky/) #-->the <<red angry sky>>
using \1-\9
show_regexp('He said "Hello"', /(\w)\1/) #-->He said "He<<ll>>o"
show_regexp('Mississippi', /(\w+)\1/) #-->M<<ississ>>ippi
show_regexp('He said "Hello"', /(["']).*?\1/) #-->He said <<"Hello">>
show_regexp("He said 'Hello'", /(["']).*?\1/) #-->He said <<'Hello'>>
|
Extensions In common with Perl and Python, Ruby regular expressions offer some extensions over traditional Unix regular expressions. – All the extensions are entered between the characters (? and ). – The parentheses that bracket these extensions are groups, but they do not generate backreferences: they do not set the values of \1 and $1 etc. | |
?# (?# comment)
Inserts a comment into the pattern. The content is ignored during pattern matching. | |
?: (?:re)
Makes re into a group without generating backreferences. This is often useful when you need to group a set of constructs but don't want the group to set the value of $1 or whatever. |
In the example that follows, both patterns match a date with either colons or spaces between the month, day, and year. The first form stores the separator character in $2 and $4, while the second pattern doesn't store the separator in an external
date = "12/25/01"
date =~ %r{(\d+)(/|:)(\d+)(/|:)(\d+)}
[$1,$2,$3,$4,$5] #-> ["12", "/", "25", "/", "01"]
date =~ %r{(\d+)(?:/|:)(\d+)(?:/|:)(\d+)}
[$1,$2,$3] #-> ["12", "25", "01"]
|
?= (?=re) Matches re at this point, but does not consume it (also known charmingly as "zero-width positive lookahead"). This lets you look forward for the context of a match without affecting $&. | In this example, the scan method matches words followed by a comma, but the commas are not included in the result. str = "red, white, and blue" str.scan(/[a-z]+(?=,)/) #-> ["red", "white"] |
?! (?!re)
Matches if re does not match at this point. Does not consume the match (zero-width negative lookahead). | For example, this matches any word that contains the letters "hot" that aren't followed by "dog", returning the end of the word in $1 "hot hotdog hotlight" =~ /hot(?!dog)(\w+)/ #-> 11 $1 #-> light |
?> (?>re)
Nests an independent regular expression within the first regular expression. This expression is anchored at the current match position. If it consumes characters, these will no longer be available to the higher-level regular expression. This construct therefore inhibits backtracking, which can be a performance enhancement. |
For example, the pattern /a.*b.*a/ takes exponential time when matched against a string containing an "a" followed by a number of "b"s, but with no trailing "a." However, this can be avoided by using a nested regular expression /a(?>.*b).*a/. In this form, the nested expression consumes all the the input string up to the last possible "b" character. When the check for a trailing "a" then fails, there is no need to backtrack, and the pattern match fails promptly.
require "benchmark"
include Benchmark
str = "a" + ("b" * 5000)
bm(8) do |test|
test.report("Normal:") { str =~ /a.*b.*a/ }
test.report("Nested:") { str =~ /a(?>.*b).*a/ }
end
produces:
user system total real
Normal: 0.410000 0.000000 0.410000 (0.414915)
Nested: 0.000000 0.000000 0.000000 (0.001190)
|
?i, ?m, ?x (?imx) Turns on the corresponding "i", "m" or "x" option. If used inside a group, the effect is limited to that group. ?-i, ?-m, ?-x (?-imx) Turns off the "i", "m", or "x" option. ?i:, ?m:, ?x: (?imx:re)
Turns on the "i", "m", or "x" option for re. ?-i:, ?-m:, ?-x: (?-imx:re)
Turns off the "i", "m", or "x" option for re. | |
.sub(/pattern/, '*') The methods String.sub and String.gsub look for a portion of a string matching their first argument and replace it with their second argument. String.sub performs one replacement, and String.gsub replaces every occurrence of the match. Both routines return a new copy of the String containing the substitutions. Mutator versions String.sub! and String.gsub! modify the original string. – The second argument to both functions can be either a String or a block. If a block is used, it is passed the matching substring, and the block’s value is substituted into the original string. \ Backslash sequences – Earlier we noted that the sequences \1, \2, and so on, are available in the pattern, standing for the nth group matched so far. The same sequences are available in the second argument of sub and gsub. – Additional backslash sequences work in substitution strings: \& (last match) \+ (last matched group) \` (string prior to match) \' (string after match) \\ (a literal backslash). | sub and gsub samples a = "the quick brown fox" a.sub(/[aeiou]/, '*') #-->"th* quick brown fox" a.gsub(/[aeiou]/, '*') #-->"th* q**ck br*wn f*x" a.sub(/\s\S+/, '') #-->"the brown fox" a.gsub(/\s\S+/, '') #-->"the"
sub & gsub with block
a = "the quick brown fox"
a.sub(/^./) {|match| match.upcase } #-->"The quick brown fox"
a.gsub(/[aeiou]/) {|vowel| vowel.upcase } #-->"thE qUIck brOwn fOx"
sub & gsub with \ "fred:smith".sub(/(\w+):(\w+)/, '\2, \1') #-->"smith, fred" "nercpyitno".gsub(/(.)(.)/, '\2\1') #-->"encryption"
|
.match – The method Regexp.match matches a regular expression against a string. If unsuccessful, the method returns nil. On success, it returns an instance of class MatchData. And that MatchData object gives you access to all available information about the match. All that good stuff that you can get from the $-variables is bundled in a handy little object. – Because the match data is stored in its own object, you can keep the results of two or more pattern matches available at the same time, something you can’t do using the $-variables. – So how do the $-variables fit in? Well, after every pattern match, Ruby stores a reference to the result (nil or a MatchData object) in a thread-local variable (accessible using $~). All the other regular expression variables are then derived from this object. Although we can’t really think of a use for the following code, it demonstrates that all the other MatchData-related $-variables are indeed slaved off the value in $~. | MatchData, special variables 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"
|
Character Classes – A character class is a set of characters between brackets: [characters] matches any single character between the brackets. [aeiou] will match a vowel, [,.:;!?] matches punctuation, and so on. The significance of the special regular expression characters .|()[{+^$*? — is turned off inside the brackets. However, normal string substitution still occurs, so (for example) \b represents a backspace character and \n a newline.
– Within the brackets, the sequence c1-c2 represents all the characters between c1 and c2, inclusive.
– If you want to include the literal characters ] and - within a character class, they must appear at the start. Put a ^ immediately after the opening bracket to negate a character class: [^a-z] matches any character that isn't a lowercase alphabetic.
– Finally, a period . appearing outside brackets represents any character except a newline (though in multiline mode it matches a newline, too).
– The sequences \d, \D, \s, \S, \w, and \W are abbreviations for groups of charactersCharacter class abbreviations \d = [0-9] – Digit character \D = [^0-9] – Nondigit \s = [\s\t\r\n\f] – Whitespace character \S = [^\s\t\r\n\f] – Nonwhitespace character \w = [A-Za-z0-9_] – Word character \W = [^A-Za-z0-9_] – Nonword character [: POSIX 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) |
Character Classes
show_regexp('Price $12.', /[aeiou]/) #-->Pr<<i>>ce $12.
show_regexp('Price $12.', /[\s]/) #-->Price<< >>$12.
show_regexp('Price $12.', /[[:digit:]]/) #-->Price $<<1>>2.
show_regexp('Price $12.', /[[:space:]]/) #-->Price<< >>$12.
show_regexp('Price $12.', /[[:punct:]aeiou]/) #-->Pr<<i>>ce $12.
a = 'see [Design Patternspage 123]'
show_regexp(a, /[A-F]/) #-->see [<<D>>esign Patternspage 123]
show_regexp(a, /[A-Fa-f]/) #-->s<<e>>e [Design Patternspage 123]
show_regexp(a, /[0-9]/) #-->see [Design Patternspage <<1>>23]
show_regexp(a, /[0-9][0-9]/) #-->see [Design Patternspage <<12>>3]
a = 'see [Design Pattern-spage 123]'
show_regexp(a, /[]]/) #-->see [Design Pattern-spage 123<<]>>
show_regexp(a, /[-]/) #-->see [Design Patterns<<->>page 123]
show_regexp(a, /[^a-z]/) #-->see<< >>[Design Pattern-spage 123]
show_regexp(a, /[^a-z\s]/) #-->see <<[>>Design Pattern-spage 123]
a = 'It costs $12.'
show_regexp(a, /c.s/) #-->It <<cos>>ts $12.
show_regexp(a, /./) #--><<I>>t costs $12.
show_regexp(a, /\./) #-->It costs $12<<.>>
|
Repetition If r stands for the immediately preceding regular expression within a pattern, then
r* — matches zero or more occurrences of r.
r+ — matches one or more occurrences of r.
r? — matches zero or one occurrence of r.
r{m,n} — matches at least “m” and at most “n” occurrences of r.
r{m,} — matches at least “m” occurrences of r.
r{m} — matches exactly “m” occurrences of r.
These patterns are called greedy, because by default they will match as much of the string as they can. You can alter this behavior, and have them match the minimum, by adding a question mark suffix (?). | Repetition a = "The moon is made of cheese" show_regexp(a, /\w+/) #--><<The>> moon is made of cheese show_regexp(a, /\s.*\s/) #-->The<< moon is made of >>cheese show_regexp(a, /\s.*?\s/) #-->The<< moon >>is made of cheese show_regexp(a, /[aeiou]{2,99}/) #-->The m<<oo>>n is made of cheese show_regexp(a, /mo?o/) #-->The <<moo>>n is made of cheese |
enumObj.find {|obj| block } -> anObject or nil Synonyms. Passes each entry in enumObj to block. Returns the first for which block is not false. Returns nil if no object matches. |
find
[1,3,5,7,9].find { |i| i > 4 } #--> 5
@songs.find {|song| title == song.name }
detect
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #-> nil
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #-> 35
|
enumObj.find_all {|obj| block } -> Array Synonyms. Returns an array containing all elements of enumObj for which block is not false enumObj.reject {| obj | block } -> Array
Returns an array for all elements of enumObj for which block is false. |
find_all
(1..10).find_all {|i| i % 3 == 0 } #-> [3, 6, 9]
reject
(1..10).reject {|i| i % 3 == 0 } #-> [1, 2, 4, 5, 7, 8, 10]
|
each animals = %w( ant bee cat dog elk ) # create an array animals.each {|animal| puts animal } # iterate over the contents [ 'cat', 'dog', 'horse' ].each {|name| print name, " " } #-->cat dog horse ('a'..'e').each {|char| print char } #-->abcde |
|
.inject Works like this: the first time the associated block is called, sum is set to inject’s parameter and element is set to the first element in the collection. The second and subsequent times the block is called, sum is set to the value returned by the block on the previous call. The final value of inject is the value returned by the block the last time it was called. There’s one final wrinkle: if inject is called with no parameter, it uses the first element of the collection as the initial value and starts the iteration with the second value. |
inject
puts [1,2,4].inject(0) {|sum, element| sum+element} #--> 0+1+2+4 = 7
puts [1,2,4].inject(1) {|product, element| product*element} #--> 1*1*2*4 = 8
#--or--
puts [1,2,4].inject {|sum, element| sum+element} #--> 1+2+4 = 7
puts [1,2,4].inject {|product, element| product*element} #--> 1*2*4 = 8
|
enumObj.sort -> Array Returns an array containing the items in enumObj sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b. | Enumerable sort %w(rhea kea flea).sort #-> ["flea", "kea", "rhea"] (1..10).sort {|a,b| b <=> a} #-> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
The following code sorts some files on modification time.
files = Dir["*"]
sorted = files.sort {|a,b| File.mtime(a) <=> File.mtime(b)}
sorted #-> ["mon", "tues", "wed", "thurs"]
This sort is inefficient: it generates two new File objects during every comparison. A slightly better technique is to use the Kernel.test method to generate the modification times directly.
files = Dir["*"]
sorted = files.sort { |a,b|
test(?M, a) <=> test(?M, b)
}
sorted #-> ["mon", "tues", "wed", "thurs"]
This still generates many unnecessary Time objects. A more efficient technique is to cache the sort keys (modification times in this case) before the sort. Perl users often call this approach a Schwartzian Transform, after Randal Schwartz. We construct a
sorted = Dir["*"].collect { |f|
[test(?M, f), f]
}.sort.collect { |f| f[1] }
sorted #-> ["mon", "tues", "wed", "thurs"]
|
enumObj.collect {| obj | block } -> Array
Returns a new array with the results of running block once for every element in enumObj. |
collect
(1..4).collect {|i| i*i } #-> [1, 4, 9, 16]
(1..4).collect { "cat" } #-> ["cat", "cat", "cat", "cat"]
collect
puts ["H", "A", "L"].collect {|x| x.succ } #-->["I", "B", "M"]
number = 2
puts( (1..10).collect {|n| n*number }.join(", ") )
# or
calc = lambda {|n| n*number }
puts( (1..10).collect(&calc).join(", ") )
produces:
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
|
enumObj.each_with_index {| obj, i | block } -> nil
Calls block with two arguments, the item and its index, for each item in enumObj. |
each_with_index
hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #-> {"cat"=>0, "wombat"=>2, "dog"=>1}
|
enumObj.to_a -> Array Returns an array containing the items in enumObj. | to_a (1..7).to_a #-> [1, 2, 3, 4, 5, 6, 7] { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a #-> [["a", 1], ["b", 2], ["c", 3]] |
enumObj.grep( pattern ) -> Array Returns an array of every element in enumObj for which Pattern === element. If the optional block is supplied, each matching element is passed to it, and the block's result is stored in the output array. | grep (1..100).grep 38..44 #-> [38, 39, 40, 41, 42, 43, 44] c = IO.constants c.grep(/SEEK/) #-> ["SEEK_END", "SEEK_CUR", "SEEK_SET"] res = c.grep(/SEEK/) {|v| IO.const_get(v) } res #-> [2, 1, 0] grep print ['Ru', 'dep', 'by'].grep(/^[^d]/) #-->Ruby File.open("ordinal").grep(/d$/) do |line| puts line end produces: second third |
enumObj.include?( Object ) -> true or false Returns true if any member of enumObj equals Object. Equality is tested using ==. | include? IO.constants.include? "SEEK_SET" #-> true IO.constants.include? "SEEK_NO_FURTHER" #-> false |
enumObj.max -> Object Returns the object in enumObj with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b. enumObj.min -> Object Returns the object in enumObj with the minimum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b. | max a = %w(albatross dog horse) a.max #-> "horse" a.max {|a,b| a.length <=> b.length } #-> "albatross" min a = %w(albatross dog horse) a.min #-> "albatross" a.min {|a,b| a.length <=> b.length } #-> "dog" |
backquote, shell `cmd` -> String
Returns the standard output of running cmd in a subshell. Command Expansion %x{cmd}
– If you enclose a string in backquotes (sometimes called backticks), or use the delimited form prefixed by %x, it will (by default) be executed as a command by your underlying operating system. The value of the expression is the standard output of that command. Newlines will not be stripped, so it is likely that the value you get back will have a trailing return or linefeed character. – The exit status of the command is available in the global variable $?. Redefining Backquotes The string is passed to the method called Kernel.` (a single backquote). If you want, you can override this. | Command Expansion `date` #-> "Sun Nov 25 23:50:57 CST 2001\n" `ls testdir`.split[1] #-> "main.rb" `ls`.split[34] #-->"book.out" %x{echo "Hello there"} #-->"Hello there\n"
Escape sequences in the command string
for i in 0..3
status = `dbmanager status id=#{i}`
end
Redefining Backquotes
alias old_backquote `
def `(cmd)
result = old_backquote(cmd)
if $? != 0
fail "Command #{cmd} failed: #$?"
end
result
end
print `date`
print `data`
produces:
Thu Aug 26 22:36:31 CDT 2004
prog.rb:10: command not found: data
prog.rb:5:in ``': Command data failed: 32512 (RuntimeError)
from prog.rb:10
|
select( readArray [, writeArray [ errorArray [timeout] ] ] ) -> anArray or nil Performs a low-level select call, which waits for data to become available from input/output devices. The first three parameters are arrays of IO objects or nil. The last is a timeout in seconds, which should be an Integer or a Float. The call waits for data to become available for any of the IO objects in readArray, for buffers to have cleared sufficiently to enable writing to any of the devices in writeArray, or for an error to occur on the devices in errorArray. If one or more of these conditions are met, the call returns a three-element array containing arrays of the IO objects that were ready. Otherwise, if there is no change in status for timeout seconds, the call returns nil. If all parameters are nil, the current thread sleeps forever. | select select( [$stdin], nil, nil, 1.5 ) # [[#<IO:0x401ba090>], [], []] |
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. This behavior is different from that of String.to_i | Integer Integer(123.999) #-> 123 Integer("0x1a") #-> 26 Integer(Time.new) #-> 1023599977 Integer("123") #-> 123 Integer("123.5") #-> invalid value for Integer: "123.5" (ArgumentError) |
Float(arg) -> Float Returns arg converted to a float. Numeric types are converted directly, nil is converted to 0.0, and the rest are converted using arg.to_f | Float Float(1) #-> 1.0 Float(nil) #-> 0.0 Float("123.456") #-> 123.456 |
String(arg) -> String Converts arg to a String by calling its to_s method. | String String(self) #-> "main" String(self.type) #-> "Object" String(123456) #-> "123456" |
Array(arg) -> Array Returns arg.to_a Merge Array Merge Array merge return array | Array Array(1..5) #-> [1, 2, 3, 4, 5] Array Merge array1=[2,1,3] array2=[4,5,6] array3 = array1 | array2 #->[2,1,3,4,5,6] |
abort Terminate execution immediately, effectively by calling Kernel.exit(1) | |
at_exit { block } -> 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. |
at_exit
def do_at_exit(str1)
at_exit { print str1 }
end
at_exit { puts "cruel world" }
do_at_exit("goodbye ")
exit
produces:
goodbye cruel world
|
autoload(Module, File) -> nil Registers File to be loaded (using Kernel::require ) the first time that Module (which may be a String or a symbol) is accessed. | autoload autoload :MyModule, "/usr/local/lib/modules/my_module.rb" |
binding -> aBinding 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. |
binding
def getBinding(param)
return binding
end
b = getBinding("hello")
eval "param", b #-> "hello"
|
block_given? -> true or false Returns true if yield would execute a block in the current context. | block_given? def try if block_given? yield else "no block" end end try #-> "no block" try { "hello" } #-> "hello" try do "hello" end |
random, randomize, rnd rand( max=0 ) -> Number Converts max to an integer using max = 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 max. – Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. srand( [ Number ] ) -> oldSeed – 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. | rand, srand srand 1234 #-> 0 [ rand, rand ] #-> [0.7408769294, 0.2145348572] [ rand(10), rand(1000) ] #-> [3, 323] srand 1234 #-> 1234 [ rand, rand ] #-> [0.7408769294, 0.2145348572] |
callcc {|cont| block } -> 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. Also see Kernel::throw for an alternative mechanism for unwinding a call stack. | |
caller( [Integer] ) -> Array Returns the current execution stack – an array containing strings in the form "file:line" or "file:line: in 'method'". The optional Integer parameter determines the number of initial stack entries to omit from the result. | caller 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( symbol ) {| | block } -> Object
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. |
catch
def routine(n)
puts n
throw :done if n <= 0
routine(n-1)
end
catch(:done) { routine(3) }
produces:
3
2
1
0
|
% sprintf( aFormatString [, arguments ]*) -> String Returns the string resulting from applying aFormatString 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 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.) Field types 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 [[visible space]-]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. 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. X – Convert argument as a hexadecimal number using uppercase letters. x – Convert argument as a hexadecimal number. Flag characters [space] (bdeEfgGioxXu) – Leave a space at the start of positive numbers. # (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. + (bdeEfgGioxXu) – Add a leading plus sign to positive numbers. - (all) – Left-justify the result of this conversion. 0 (zero) (all) – 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. |
sprintf
sprintf("%d %04x", 123, 123) #-> "123 007b"
sprintf("%08b '%4s'", 123, 123) #-> "01111011 ' 123'"
sprintf("%*2$s %d", "hello", 10) #-> " hello 10"
sprintf("%*2$s %d", "hello", -10) #-> "hello -10"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #-> "+1.23: 1.23:1.23"
1250799.99 -> 1'250'799.<u>99</u>$
v = 1250799.99
sprintf("%s.<u>%02d</u>$", v.to_i.to_s.gsub(/(\d)(?=\d{3}$|\d{6}$)/, '\1\''), v*100%100)
produces:
1'250'799.<u>99</u>$
|
CGI.escapeElement( String [, elements ]* ) -> NewString Returns a string made from the given argument with certain HTML-special characters escaped. The HTML elements given in elements will be escaped; other HTML elements will not be affected. CGI.unescapeElement( String [, elements ]* ) -> NewString Returns a string with the selected escaped HTML elements expanded to the actual characters. |
escapeElement
print CGI::escapeElement('<BR><A HREF="url"></A><P>', "A", "IMG")
produces:
<BR><A HREF="url"></A><P>
|
CGI.escapeHTML( String ) -> NewString Returns a string made from the given argument with HTML-special characters (such as "&",""","<",">") quoted using "&", """, "<", ">", and so on. CGI.unescapeHTML( String ) -> NewString Returns a string made from the given argument with HTML-special quoted characters expanded to the actual characters. | |
CGI.escape( String ) -> NewString Returns a URL-encoded string made from the given argument, where unsafe characters (not alphanumeric, "_", "-", or ".") are encoded using "%xx" escapes. CGI.unescape( String ) -> NewString Returns a string containing "unsafe" characters made from the given URL-encoded argument, where unsafe characters were encoded using "%" escapes. | |
CGI.pretty( HTMLString, LeaderString=" " ) -> Session Formats the given 'HTMLString' in a nice, readable format, optionally prefixing each line with 'LeaderString'. | |
CGI.parse( String ) -> Hash Parses a query string and returns a hash of its key-value pairs. | |
CGI.rfc1123_date( Time ) -> String Returns a string representing the given time according to RFC 1123. | rfc1123_date require 'CGI' puts CGI::rfc1123_date( Time.at(1174481654) ) produces: Wed, 21 Mar 2007 12:52:50 GMT |
Session.send( String, flags, [, to ] ) -> Fixnum Sends "String" over "Session". If specified, "to" is a struct sockaddr specifying the recipient address. "flags" are the sum or one or more of the MSG_ options. Returns the number of characters sent. | |
Session.send( String, flags ) -> Fixnum The two-parameter form sends "String" on an existing connection. The four-parameter form sends "String" to port on hostName. | |
Session.sendmail( src, from, to ) Sends header and body lines to the sendmail server. The from parameter is used as the sender's name in the MAIL FROM: command, and to is either a string or an array of strings containing the recipients for the RCPT TO: command. Lines to be sent are fetched by invoking src.each. The terminating '.' and QUIT are sent automatically. | |
|
|