(based on Ruby for Rails by David  REGULAR EXPRESSION (REGEXP) Black) /([a-z]+)/ Compiled by Acap @ rubynerds.blogspot.

com

Ruby Built­ins  Cheatsheet

Or 0...10

COMPARISON METHOD
Definition def ==(x) def > (x) def < (x) def >= (x) def <= (x) Calling example obj.+(x) obj.–(x) obj.*(x) obj./(x) obj.%(x) Sugared syntax obj + x obj – x obj * x obj / x obj % x Calling example obj.==(x) obj.>(x) obj.<(x) obj.>=(x) obj.<=(x) Sugared syntax obj == x obj > x obj < x obj >= x obj <= x

SYNTACTIC SUGAR ARITHMETIC
Definition def + (x) def – (x) def * (x) def / (x) def % (x) How ruby sees it x = x + 1 x = x – 1 x = x * 2 x = x / 2 x = x % 2

The Basics
LITERAL CONSTRUCTORS STRING
“new string” Or 'new string'

CASE EQUALITY (FOR CASE/WHEN)
Definition def === (x) Calling example obj.===(x) Sugared syntax obj === x

BANG METHODS
The bang methods are defined with an exclamation mark - ! -. These methods are user-definable, however, by default, they usually mean that they, unlike their non-bang equivalents, modify their receivers. Examples: str = “hello” puts str.upcase #output: HELLO puts str #output: hello puts str.upcase!#output: HELLO puts str #output: HELLO

SYMBOL
Or

:symbol :”symbol with spaces”

Sugared syntax x += 1 x –= 1 x *= 2 x /= 2 x %= 2

ARRAY
Square brackets [1,2,3,4,5]

HASH
Curly braces {}

GET/SET/APPEND DATA
Definition def [](x) def []= (x,y) def << (x) Calling example obj.[](x) obj.[]=(x,y) obj.<<(x) Sugared syntax obj [ x] obj [ x]= y obj << x

Built – Ins
BUILT-IN CONVERSION METHODS
to_s to_i to_a to_f #to #to #to #to string integer array float

{“New York” => “NY”, “Oregon” => “OR”}

RANGE
Two or three dots 0..10

These methods are defined by default for most objects. However, you can also define them for your objects using the standard def statement.

Strings and Symbols
STRING QUOTING MECHANISM
Token Example 'You\'ll have to “escape” single quotes' “You'll have to \”escape\” double quotes” %q{'Single quoted' example – no escape} %Q{“Double quoted” example – no escape} ' ' “ “ %q %Q

str = “RUBY” str.downcase str = “Ruby” str.swapcase str.chop str = “ Ruby “ str.strip str.lstrip str.rstrip str = “Ruby\n” str.chomp
STRUNG GET/SET METHODS

#output: “ruby” #output: “rUBY” #output: “Rub” #output: “Ruby” #output: “Ruby ” #output: “ Ruby” #output: “Ruby”

BUILT-IN EQUALITY TESTS
Apart from the usual comparison operators, the following methods are also built-in for most objects. obj.eql? obj.equal?

COMPARABLE

class Bid include Comparable attr_accessor :contractor attr_accessor :quote #This is called the spaceship #operator – must always return -1, 1, #or 0 def <=>(other_bid) if self.quote < other_bid.quote -1 elsif self.quote > other_bid.quote 1 else 0 end end end

COMBINING STRINGS

“a” + “b” + “c” str = “Hi ” puts str + “There” #output: Hi There puts str #output: Hi puts “#{str}There” #output: Hi There puts str #output: Hi puts str << ”There”#output: Hi There puts str #output: Hi There

Getter methods ( [ ] ) str = “abc” puts str[2] #output:99 (ASCII value c) puts str[2].chr #output: c puts str[1,2] #output: bc Setter methods ( [ ]=) str = “abc” puts str[2] = “d” #output: abd puts str[1,2] = “ge” #output: age

REPLACING A STRING'S CONTENTS
str = “Hi There” puts str #output: Hi There str.replace(“Goodbye”) puts str #output: Goodbye

STRING COMPARISONS

Once this function is defined, use it by using the usual less_than, larger_than or equal_to operators a < b a > b a == b

“a” == “a” “a”.eql?(“a”)

This function checks if the two strings are equal objects “a”.equal?(“a”) Larger than or less than comparisons compare ASCII values of the characters in a string “a” < “b” #output: true “a” < “A” #output: true

MASSAGING STRINGS

str = “ruby” str.capitalize str.reverse str.upcase

#output: “Ruby” #output: “ybur” #output: “RUBY”

SYMBOLS
only one symbol object can exist for any given unit of text :a :venue “a”.to_sym “a”.intern

NON-DECIMAL NUMBERS
Hexadecimal integers 0x12 #equals 18 Octal integers (begin with 0) 012 #equals 10

t.strftime(“%m-%d-%Y”) Specifier %Y %y %b, %B Description Year (4 digits) Year (las 2 digits) Short month, full month Month (number) Day of month (left padded with zeros) Day of months(left padded with blanks) Short day name, full day name Hour (24h), hour (12h am/pm) Minute Second Equals “%a %b %d %H:%M:%S %Y” Equals “%m/%d/%y”

UNIQUENESS OF SYMBOLS

:a.equal?(:a) #output: true

RAILS STYLE METHOD ARGUMENTS
<%= link_to "Click here", :controller => "book", :action => "show", :id => book.id %>

to_i conversion from any base to decimal. Supply the base %m to convert from as argument to to_i %d “10”.to_i(17) #result: 17 “12345”.to_i(13) #result: 33519 %e

Times and Dates
Manipulated through three classes: Date Time DateTime 'require' the classes into your program to use them

%a, %A %H, %I %M %S %c %x

Numerical Objects
SENDING MESSAGES TO NUMBERS
x=12 x.zero?

n = 98.6 m = n.round ascii_value = 97.chr str = 2.ro_s

METHODS

d = Date.today #returns today's date puts d << 2 #rewind date by 2 months puts d >> 5 #advance date by 5 months t = Time.new t.year t.month t.day t.hour t.min t.sec t.usec

Arrays and Hashes
CREATING ARRAYS
a = Array.new a = [] a = [1,2, “three”, 4] You can initialize Array size and contents using Array.new Array.new(3) #output: [nil,nil,nil] Array.new(3, “abc”) #output: [“abc”, “abc”, “abc”] Array.new can also take code blocks n = 0

COMMON ARITHMETIC EXPRESSIONS
Expression 1 + 1 10/3 10.0/3.0 Result 2 3 Description Addition Integer Division Subtraction negative number

3.333333 Floating-point Division

-12 - - 7 -5

Array.new(3) {n +=1; n * 10}

numbers = a.zip(b).flatten #[0,1,2,3,4,5] h.empty? numbers.reverse puts numbers numbers.!reverse puts numbers #[5,4,3,2,1,0] h.include?(item) #[0,1,2,3,4,5] #[5,4,3,2,1,0] h.any?{|item| #[5,4,3,2,1,0] test} h.all?{|item| test}

True if array is empty True if item is in array True if any values in array passes test in code block True if all values in array passes test in code block

INSERTING, RETRIEVING AND REMOVING
Inserting a = [] a[0] = 1 #[1] a[1,2] = 2,3 #[1,2,3] Retrieving a # [1,2,3] a[2] # 3 a[0,2] # [1,2] Special methods for beginnings and ends of arrays a = [1,2,3,4] a.unshift(0) #[0,1,2,3,4] a = [1,2,3,4] a.push(5,6,7) #[1,2,3,4,5,6,7]

[“abc”,“def”,123].join #”abcdef123” [“abc”,“def”,123].join(“, “) #”abc, def, 123”

Or, if you want to 'push' just one argument, a = [1,2,3,4] a << 5 #[1,2,3,4,5] popd = a.pop puts popd shiftd = a.shift puts shiftd #[1,2,3,4] # 5 #[2,3,4] # 1

c = [1,2,1,3,4,5,6,4] c.uniq #[1,2,3,4,5,6] puts c #[1,2,1,3,4,5,6,4] CREATING HASHES h = {} c.!uniq #[1,2,3,4,5,6] h = Hash.new puts c #[1,2,3,4,5,6] h = Hash.new(0) #specify a default value h = Hash[ “Connecticut”=> “CT” ARRAY ITERATION, FILTERING AND QUERYING “Delaware” => “DE”] h = { “Connecticut”=> “CT” [1,2,3,4,5].each {|x| puts x*10} “Delaware” => “DE” [1,2,3,4,5].each_with_index do |x,i| “New Jersey” => “NJ” puts “element #{i} is #{x}” “Virginia” => “VA” ) end Note: '=>' can be interchanged with ',' for hashes The map method returns a new array a = [1,2,3,4,5].map {|x| puts x * 10} This filter finds first occurrence of criteria in code block [1,2,3,4,5,6,7].find{|n| n > 5} This filter finds all occurences of criteria in code block [1,2,3,4,5,6,7].find_all{|n| n > 5} To create a hash which sets every non-existent key it gets to a default value, use code blocks h = Hash.new {|hash, key| hash[key] = 0}

COMBINING ARRAYS

ADDING TO A HASH
state_hash[“New York”] = “NY” state_hash.store(“New York”, “NY”)

a = [1,2,3] b = a + [4,5,6] #[1,2,3,4,5,6] This filter removes all occurences of criteria in code block puts a #[1,2,3] [1,2,3,4,5,6,7].reject{|x| x > 5} a.concat{[4,5,6]} #[1,2,3,4,5,6] puts a #[1,2,3,4,5,6] a.replace{[4,5,6]} #[4,5,6] ARRAY QUERYING a.zip{[7,8,9]} #[[4,7],[5,8],[6,9]] Method + Sample call Description Returns the number of values in array

RETRIEVING FROM A HASH

state = state_hash[“New York”] state = state_hash.fetch(“New York”)

ARRAY TRANSFORMATIONS

To retrieve values from multiple keys, states = state_hash.values_at(“New York”, “Delaware”)

a = [0,2,4] h.size b = [1,3,5] numbers = a.zip(b) #[[0,1],[2,3],[4,5]]

COMBINING HASHES
h1 = {“Smith => “John”}

h2 = {“Jones” => “Jane”} h1.update(h2) key in h1, then h1's key – value is overwritten h3 = h1.merge(h2) a third hash and h1 and h2 keeps their contents

Method + Sample call

Description True is h has the key 1 Same as has_key? Same as has_key? Same as has_key? True if any value in h is “three” Same as has_value? True if h is empty Number of key/value pairs in h

once each is defined, there are many methods available to the class. Enumerable.instance_methods(false).sort provides a list of methods available. The functions sort and sort_by require the following to be done: 1. 2. Define a comparison method '<=>' Place objects in a container, (e.g. Array)

using the update method, if h2 has a key that is similar to a h.has_key?(1) h.include?(1)

using the merge method, the combined hash is assigned to h.key?(1) h.member?(1) h.has_value? (“three”) h.value(“three”) h.empty? h.size

HASH TRANSFORMATIONS
h = {1 => “one”, 2 => “two”} h.invert #{“two” => 2, “one” => 1} h.clear #{} h.replace({10=>”ten”,20=>”twenty”}) #output: {10=>”ten”, 20=>”twenty”}

HASH ITERATION, FILTERING AND QUERYING

h.each do |key,value| puts “Word for #{key} is #{value}” end

THE ENUMERABLE MODULE
Include Enumerable and define an each method for your

Example: Class Edition etc... def <=>(other_edition) self.price <=> other_edition.price end end price_sort = [ed1,ed2,ed3,ed4,ed5].sort

For iterating through all the keys/values h.keys #{10, 20} h.values #{“ten, “twenty”} Or h.each_key{|k| #code here } h.each_value{|v| #code here } For filtering through hashes h.select{|k,v| k > 10} The find method returns the first matching element in the hash. h.find {|k,v| k > 10} The map method on a hash returns a new array new_hash = h.map {|k,v| k > 10}

class to enable your class to perform the following methods You could also do sorting by defining the sort order in a select code block reject year_sort = [ed1,ed2,ed3].sort do |a,b| find a.year <=> b.year map end Example: ["2",1,5,"3",4,"6"].sort do |a,b| class Colors a.to_i <=> b.to_i include Enumerable end def each yield “red” yield “green” the sort_by method helps to sort different types of values by yield “blue” taking in a code block that tells it how to handle different yield “yellow” end types of values end ["2",1,5,"3",4,"6"].sort_by do |a| r = Colors.new a.to_i y_color = r.find {|col| col[0,1] == 'y'} end puts “First color with y is #{y_color}”

HASH QUERYING

Regular Expressions
THE REGEX LITERAL CONSTRUCTOR
is a pair of forward slashes : - / /

{ }

/\d{3}-\d{4}/ Number/Range of /\d{1,10}/ Repetition character /([A-Z]\d) {5}/ /[^a-z]/ Atom character Negative character (in character classes) Zero or One character One or More character Zero or More character Non-greedy One or More / Zero or More Lookahead assertion Negative Lookahead assertion

\S

/\S/

Match any nonwhitespace character

( ) ^

Regex anchors Notation ^ $ \A \z \Z Usage example /^\s*#\ /\.$/ /\AFour score/ /earth.\z/ /earth.\Z/ Description Beginning of line anchor End of line anchor Beginning of string End of string End of string (except for final newline) \b /\b\w+\b/ Word boundary ex.” !!! word***” (matches “word”) Regex modifiers

PATTERN MATCHING OPERATION
Or

/abc/.match(“abcdefghi”) “abcdefghi”.match(/abc/) “abcdefghi” =~ /abc/ /abc/ =~ “abcdefghi”

? + * +? / *?

/Mrs?/ /\d+/ /\d*/ /\d+?/ or /\d*?/ /\d+(?=\.)/ /\d+(?!\.)/

Note: match returns MatchData, while =~ returns index of character in string where match started

BUILDING A REGEX PATTERN
Literal characters Digits, alphabets, whitespaces, underscores etc. /abc/ /019/

?= ?!

Special escape sequences Special characters Need to be preceded by '\' to be included as a matching Notation \d Usage example /\d/ /\D/ /\w/ Description Match any digit Match other than digit Match any digit, alphabet, and underscore \W /\W/ Match other than digit, alphabet, and underscore \s /\s/ Match any whitespace character

Notation i m

Usage example /abc/i /\(.*?\)/m

Description Case-insensitive mod Multiline modifier

pattern ^, $, ?, ., /, \, [, ], {, }, (, ), +, * \D Notation . / \ [ ] Usage example /.ejected/ // / \? / /[a-z]/ Description Wildcard character Regex literal constructor Escape character Character class \w

Wildcard character '.' (dot) /.ejected/ #matches rejected & dejected Character classes (in [ ]) /[dr]ejected/ #matches d or r +ejected /[a-z]/ #matches any lowercase letter

puts “1st match:#{$1} & 2nd:#{2}” /[A-Fa-f0-9]/ #matches any hexadecimal digit Lookahead assertions To match numbers only if it ends with a period, str = "123 456. 789" m = /\d+(?=\.)/.match(str) Strings and regex interchangeability String to regex str = “def” /abc#{str}/ str = “a.c” re = /#{Regexp.escape(str)}/ # = /a\.c/ From regex to string puts /abc/ #output: (?-mix:abc) p /abc/ #output: /abc/ m[0] m[1],m[2],etc m.pre_match

scan goes from left to right thru a string, looking for a match

for the pattern specified. Results are returned in an array. MatchData “testing 1 2 3 testing 4 5 6”.scan(/\d/) string = “My number is (123) 555-1234.” returns the array: pattern =/\((\d{3})\)\s+(\d{3})-(\d{4})/ [“1”, “2”, “3”, “4”, “5”, “6”] m = pattern.match(string) if regex is parenthetically grouped, then scan returns an array of arrays. Method + Sample call m.string Description Returns the entire string matched m.captures(index) Returns the submatch referenced by index (start from 0) Entire match Same as captures (start from 1) Returns part of string before match Returns part of string after match Returns the position of 1 referenced by index m.end(index) Returns the position of last character matched in
st

String#split Split splits a string into multiple substrings and returns them in an array. Split can take a regex or a regular string as argument “Ruby”.split(//) line = "first=david;last=black;country=usa" record = line.split(/=|;/) String#sub/sub!/gsub/gsub! sub and gsub are methods for changing the contents of strings in Ruby. Gsub makes changes throughout a string, while sun makes at most one substitution. Bang equivalents modify its receivers.

MATCHDATA AND GLOBAL VARIABLES
When a regex matching is performed with parenthetical

m.post_match groupings: /([A-Za-z]+), [A-Za-z]+(Mrs?\.)/ .match(str) the results of the match (submatches), if any was found, is: 1) 2) Ruby populates a series of global variables to access those matches Returned in the form of MatchData Note: if no match found, match returns nil Global variables Are populated by order of matches according to numbers. First match, $1, second, $2 etc: $1, $2, $3 Example use m.begin(index)

character matched in submatch sub

“typigraphical error”.sub(/i/, “o”)

Or using code blocks, “capitalize the first vowel”. sub([aeiou]/){|s| s.upcase}

METHODS THAT USE REGEX
String#scan

submatche referenced by index gsub “capitalize every word”.gsub(/\b\w/) {|s| s.upcase} Using sub and gsub captures in replacement string, using \1, \2, \3 etc:

“aDvid”.sub(/([a-z])([A-Z]), '\2\1') grep

eval("def #{m}; puts 'Hi!'; end") eval(m) whenever the code is run and user types in a name, a

CALLABLE OBJECTS
Proc objects Proc objects are closures. a Proc object is created with a code block that isn't executed until the Proc object is called with the call method pr = Proc.new {puts “Proc code block”} pr.call #output: “Proc code block” Proc objects are closures – it retains the scope from where

grep does a select operation on an array based on a regex method by that name is then created. argument. Note: the code above lets users in on program definition. [“USA”, “UK”, “France”, “Germany”]. Given the right commands, eval lets users hack into your grep(/[a-z]/) program, and even system. grep can also take code blocks ["USA", "UK", "France", "Germany"]. grep(/[a-z]/) {|c| c.upcase } instance_eval Evaluates string or code block given to it, changing self to be the receiver of instance_eval p self a = [] a.instance_eval(p self)

Ruby Dynamics
SINGLETON CLASSES
To get inside the definition body of a singleton class, class << object #method and constant definitions end Class methods can be defined this way within the body of the class definition: class Ticket class << self #method and constant definition end etc... end

THE EVAL FAMILY OF METHODS
eval eval executes the string given to it. Eval(“2+2”) eval lets you, for example, allow program users to give a method their own name print "Method name: " m = gets.chomp

it is originally created def call_some_proc(pr) #output: main a = "irrelevant 'a' in method scope" puts a #output: [] pr.call This method is useful for obtaining acces to another object's end private data. a = "'a' to be used in Proc block" class C pr = Proc.new { puts a } def initialize pr.call @x = 1 call_some_proc(pr) end end The output for the above is as follows: c = C.new 'a' to be used in Proc block c.instance_eval {puts @x} irrelevant 'a' in method scope 'a' to be used in Proc block class_eval (a.k.a module_eval) Proc objects can take arguments This method puts you inside a class definition body pr = Proc.new {|x| p x} var = “var” pr.call(100) class C puts var #returns NameError end If Proc takes more than one argument, extra arguments on either side of the transaction are ignored pr = Proc.new{|x,y,z| p x,y,z} pr.call(1,2) To define an instance method using an outer-scope variable #output: 1 # 2 with class_eval, use the define_method method. # nil C.class_eval { define_method("talk") pr.call(1,2,3,4) { puts var }} C.class_eval {puts var} #returns “var”

same class or subclass of the original object. class D < C lambda end d = D.new lambda creates an anonymous function lam = lambda{puts “A lambda!”} unbound = meth.unbind lam.call #output: “A lambda!” unbound.bind(d).call lambda is a subclass of Proc. The difference from Proc is lambda returns from lambda, Proc returns from the method it's encapsulated in. Convert code blocks into Proc objects by capturing the blocks in a variable using &. def grab_block(&block) block.call end grab_block { puts "in '&block'" } You can also convert a Proc/lambda object to a code block using & lam = lambda {puts "lambda code block"} grab_block &lam Methods as objects methods objects can be obtained using the 'method' method class C def talk puts "self is #{self}." end end c = C.new meth = c.method(:talk) meth.call #output: self is #<C> by default, self is the class where method is defined. To

#output: # #

1 2 3

unbind self and bind to another object, use unbind and bind method. This can only be done if the other object is the end

by #{subclass}" end class D < C end Note: inherited functions are inherited by its subclasses. Subclasses of the subclasse will also trigger inherited. Module#const_missing This method, if defined, is executed whenever an unidentifiable constant is referred to inside a given module or class. class C def self.const_missing(const) puts "#{const} is undefined—setting it to 1." const_set(const,1) end end puts C::A puts C::A

CALLBACKS AND HOOKS
method_missing class C def method_missing(m) puts "No method called #{m} -please try again." end end C.new.anything Module#included If defined for a module, executes the method whenever module is mixed in (included) in a class module M def self.included(c) puts "I have been mixed into #{c}." end end class C include M end Class#inherited If defined for a class, executes the method whenever class is inherited by another class(subclass). class C def self.inherited(subclass) puts "#{self} just got subclassed

OVERRIDING AND ADDING TO CORE FUNCTIONALITY
Ruby's core functionality can always be redefined easily class Array def shuffle sort_by { rand } end end Note: be careful, as you may cause problems if your program is shared with other developers.

Sign up to vote on this title
UsefulNot useful