Ruby [about]

What is Ruby?

Syntax

#-> this is a string #{var}

produces: Double quoted here document. Sum = 124 This is single quoted. The above used #{a + 1}

document here , here document , HereDoc

#swap the values in two variables

# assigns each element of the array returned to the variables (See parallel assignment, below)

# Really a return of an array.

#creates only writable member of class

# you could write the following to process the lines in a file.

# Ruby treats nil as a false value in conditions,

Boolean Expressions

Bitwise Operators [bit by bit operations, bits level operations, working with bits]

Symbols [:, symbol]

# instead of

# so it can not be used everywhere

symbol to integer , symbol to number

:" , .to_sym , string 2 symbol , string to symbol , to symbol , to_sym

Variables

Array class [Array, Array class, arrays, list, rray]

all? , any?

all? , any? , logical iterators

.last , array last , last item , last n elements , last n items

.first , array first , first n

.each , array each

.delete_at , array delete element , array delete_at , delete at , delete by index , delete element from array

.delete , array delete , array delete elements , array elements deletion , delete all , delete by content match , delete from array

# prints: a, b, c, a, b, c

# prints: a, b, c, a, b, c, ... (forever)

#-> [] # no combinations of length 5

#-> [[]] # one combination of length 0

# here multiple copies are created

# only one copy of the object is created

# set the third element

#-> 1 access the first element

# create array with three elements

Hashes [Hash, hsh]

produces: prog.rb:2:in `fetch': key not found (IndexError) from prog.rb:2

produces: a is 100 b is 200

.each , each hash , each hsh

Ranges [Range]

produces: first second third eighth ninth

Blocks and Iterators

# the file when it returns

# If there's a block, pass in the file and close

produces: Start of method In the block In the block End of method

# santa objects are called, its value is still available to the closures.

# Even though the parameter “n” is out of scope when the double and

# shows this in action.

# which is passed to the block as a parameter. The following code

#The block multiplies the method’s parameter, “n”, by another value,

#-> will raise an exeption "wrong number of arguments (2 for 3) (ArgumentError)"

return from blocks , returning in blocks

#-->"Hello Hello Hello "

# produces: This is line one This is line two This is line three And so on...

# and calculate next

# invoke block with passing value

Control Structures

else if , elseif

Loops [cycle]

produces: second third

cycle , for in , for-in , forin , loop

cycle , each_with_index , for in , for-in , forin , loop

# substitute stuff in backticks and try again

produces: third fourth fifth

produces: prog.rb:4: undefined local variable or method `x' for main:Object (NameError)

Classes, Modules, Mixins, and Multiple Inheritance

class name , class of variable , get class , object class , variable class

produces: This is a sample documentation string And this is a documentation string in a module

# ('<=' for classes checks for same class or subtype)

# If we're passed a class or module, convert to string

#include it into another file:

# in some third program

# ... and so on

# and this will be 'public'

# subsequent methods will be '=public'

# will be 'private'

# subsequent methods will be '=private'

# will be 'protected'

# subsequent methods will be '=protected'

# the object’s attribute never got updated. This can be a tricky bug to

# so Ruby stored the new value in a local variable of method volume=;

# We forgot to put “self.” in front of the assignment to left_channel,

# class without a receiver. This is because class is also a keyword in Ruby

# we could not call the method

#-> "Got one and two, three"

#-> "Got one and two"

#-> "Got one and "

# def [] invokes by songObj[7] with 7 as parametr

Module

produces: Picky added to Array Can't add Picky to a String

Object

#-> "Hello from Mod.

"

#-> "Hello from Klass.

"

produces: prog.rb:4:in `[]=': can't modify frozen string (TypeError) from prog.rb:4

# prevent modifications to the object

produces: prog.rb:3:in '<<': can't modify frozen array (TypeError) from prog.rb:3

Numeric

Integer [Fixnum]

Float

Bignum

String class [String, strings, working with strings]

#, Substitutions "...#{expr } ...#$globalExp...#@classExp...#@@const..." Double-quoted strings support a boatload more escape sequences. The most common is probably

, 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 .

Substitutesr = '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...



quoting, 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.

Quoting%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.

escaping escape using "\"'escape using "\\"' #-> escape using "\" 'That\'s right' #-> That's right

usingline = "/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.

usage"%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

str << Object → str

synonyms

str.concat( Fixnum ) → str

str. concat ( Object ) → 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.

samplea = "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

str === Object → true or false (Synonym) 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

str [Fixnum, Fixnum] → String or nil

str [Range] → String or nil

str [Regexp] → String or nil

str [String] → String 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.

samplesa = "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

str [Fixnum] = String

str [Fixnum, Fixnum] = String

str [Range] = String

str [Regexp] = String

str [String] = String 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.

samplesa = "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"



String functions in Ruby String methods Source: ellho.net/solutions/ruby-string-functions-in-ruby.html To change case: capitalize - first character to upper, rest to lower downcase - all to lower case swapcase - changes the case of all letters upcase - all to upper case To rejustify: center - add white space padding to center string ljust - pads string, left justified rjust - pads string, right justified To trim: chop - remove last character chomp - remove trailing line separators squeeze - reduces successive equal characters to singles strip - deletes leading and trailing white space To examine: count - return a count of matches empty? - returns true if empty include? - is a specified target string present in the source? index - return the position of one string in another length or size - return the length of a string rindex - returns the last position of one string in another slice - returns a partial string To encode and alter: crypt - password encryption delete - delete an intersection dump - adds extra \ characters to escape specials hex - takes string as hex digits and returns number next or succ - successive or next string (eg ba → bb) oct - take string as octal digits and returns number replace - replace one string with another reverse - turns the string around slice! - DELETES a partial string and returns the part deleted split - returns an array of partial strings exploded at separator sum - returns a checksum of the string to_f and to_i - return string converted to float and integer tr - to map all occurrences of specified char(s) to other char(s) tr_s - as tr, then squeeze out resultant duplicates unpack - to extract from a string into an array using a template To iterate: each - process each character in turn each_line - process each line in a string each_byte - process each byte in turn upto - iterate through successive strings (see "next" above)



str.slice( Fixnum ) → Fixnum or nil

str. slice ( Fixnum, Fixnum ) → String or nil

str. slice ( Range ) → String or nil

str. slice ( Regexp ) → String or nil

str. slice ( String ) → String or nil Synonyms for str[]

slicea = "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

str. slice! ( Fixnum, Fixnum ) → String or nil

str. slice! ( Range ) → String or nil

str. slice! ( Regexp ) → String or nil

str. slice! ( String ) → String 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"



to uppercase 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

nn 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



indexOf str.index( String [, Offset ] ) → Fixnum or nil

str. index ( Fixnum [, Offset ] ) → Fixnum or nil

str. index ( Regexp [, 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

str. rindex ( Fixnum [, Fixnum ] ) → Fixnum or nil

str. rindex ( Regexp [, 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



string to array 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", "", ""]



.strip 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

".strip #-> "goodbye" " first second third

".strip #-> "first second third"



str.reverse → String

str.reverse! → str Returns a new string with the characters from str in reverse order . "reverse!" reverses str in place.

reverseputs "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

".chomp #-> "hello" "hello

there".chomp #-> "hello

there" "hello".chomp("llo") #-> "he"



str.chop → String Returns a new String with the last character removed . If the string ends with \r

, 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

".chop #-> "string" "string

\r".chop #-> "string

" "string

".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 .

counta = "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



delete string, str delete, string delete 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'



each line, each string, eachline, string each str.each( String=$/ ) {| substr | block } → str

str.each_line( String=$/ ) {| substr | block } → str (Synonym) 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

characters, except that multiple successive newlines are appended together .

eachprint "Example one

" "hello

world".each {|s| p s} print "Example two

" "hello

world".each('l') {|s| p s} print "Example three

" "hello





world".each(") {|s| p s} produces: Example one "hello

" "world" Example two "hel" "l" "o

worl" "d" Example three "hello





" "world"



each byte 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

str. sub ( pattern ) {| match | block } → 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

str. sub! ( pattern ) {| match | block } → 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

str. gsub ( pattern ) {| match | block } → 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

str. gsub! ( pattern ) {| match | block } → 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 iclude, string include str.include? String → true or false

str. include? Fixnum → 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

str.size → Integer (Synonym) Returns the length of str.



str.replace( String ) → str Replaces the contents and taintedness of str with the corresponding values in String.

replaces = "hello" #-> "hello" s.replace "world" #-> "world"



.scan str.scan( pattern ) → Array

str. scan ( pattern ) {| match, ...| block } → str 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.

scana = "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 "

" a.scan(/(.)(.)/) {|a,b| print b, a } print "

" 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

str.next → String (Synonym) 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

str.next! → str (Synonym) 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"



to Float 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.



.tr, 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"]



nn, \xxx Cyrillic unpack"\320\240\320\270".to_a.pack('A*') --> 'Ри'

