100% found this document useful (13 votes)
3K views

Ruby Cheatbook

Ruby Syntax and Built-Ins Cheatbook. Part 1 and 2 of the Ruby Cheatsheets in 1 file. Based on 'Ruby for Rails' by David Black

Uploaded by

Asyraf
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (13 votes)
3K views

Ruby Cheatbook

Ruby Syntax and Built-Ins Cheatbook. Part 1 and 2 of the Ruby Cheatsheets in 1 file. Based on 'Ruby for Rails' by David Black

Uploaded by

Asyraf
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Ruby Cheatbook To 'print out' result of execution in HTML

Based on Ruby for Rails NUMBER TO STRING CONVERSION <%=#Ruby code in here%>

by David Black x = 100.to_s
x = 100 CODE BLOCKS
string = x.to_s
Compiled by Asyraf.  Any code defined within {} or do end
{#code}
rubynerds.blogspot.com
COMPARING TWO VALUES OR
x == y do
Part 1 #code here
end
COMMENTING
The Basics #This is a comment!
LITERAL CONSTRUCTORS
ARITHMETIC FILE HANDLING Type Constructor Example
2 + 3
File writing “” or '' “abc” or 'abc'
2 – 3 String
2 * 3 fh = File.new(“filename.dat”, “w”)
: :symbol or
2 / 3 fh.puts x #x is imaginary variable here Symbol
fh.close :”symbol with spaces”
[] [1,2,3,4,5]
PRINTING TO THE SCREEN Array
puts “Hello” File reading {} {“New York” => “NY”
fh = File.read(“filename.dat”) Hash
print “Hello” “Oregon” => “OR”}
p “Hello”
.. or ... 0..10 or 0...10
Range
x = “Hello” EXTERNAL CODE INCLUSION
// /([a-z]+)/
puts x require “filename.rb” Regexp
print x Or
p x load “filename.rb”
SYNTACTIC SUGAR
GETTING INPUT FROM THE SCREEN STRING INTERPOLATION Arithmetic
gets x=1 Definition Calling example Sugared syntax
string = gets puts “x is equal to: #{x}”
def + (x) obj.+(x) obj + x

STRING TO NUMBER CONVERSION EMBEDDED RUBY def – (x) obj.–(x) obj – x


def * (x) obj.*(x) obj * x
x = “100”.to_i To embed Ruby code in HTML
<%#Ruby code in here%> def / (x) obj./(x) obj / x
string = “100”
x = string.to_i def % (x) obj.%(x) obj % x

Ruby Cheatbook by rubynerds.blogspot.com


Incrementals These methods are user-definable, however, by default, INSTANCE VARIABLES
Sugared syntax How ruby sees it they usually mean that they, unlike their non-bang
Refer to Instance Variables in Classes
x += 1 x = x + 1 equivalents, modify their receivers. Examples:
str = “hello”
x –= 1 x = x – 1 puts str.upcase #output: HELLO
Methods
puts str #output: hello
x *= 2 x = x * 2 METHOD DEFINITION
x /= 2 x = x / 2 def method1(x)
puts str.upcase!#output: HELLO
x %= 2 x = x % 2 puts str #output: HELLO value = x + 1
return value
end
Get/Set/Append data
Variables and Constants
Definition Calling example Sugared syntax CONSTANTS METHOD ARGUMENTS
def [](x) obj.[](x) obj [ x] Constants start with a capital letter Definition Description
def []= (x,y) obj.[]=(x,y) obj [ x]= y Constant = “Hi!” def method(a,b,c) Fixed number of arguments
def << (x) obj.<<(x) obj << x
CONSTANT RESOLUTION IN NESTED CLASSES/MODULES def method(*a) Variable number of args
Class M def method(a=1,b=2)
Comparison method Module N Default value for arguments
Class O def method(a,b=1,*c)
Definition Calling example Sugared syntax Class P Combination arguments
def ==(x) obj.==(x) obj == x X = 1 NOTE: def method(a, *b, c) is not allowed! Arguments with
end
def > (x) obj.>(x) obj > x end * must always be at the end of the argument definition
def < (x) obj.<(x) obj < x end
end
def >= (x) obj.>=(x) obj >= x BOOLEAN METHODS
def <= (x) obj.<=(x) obj <= x The constant is accessed by def ticket.available?
puts M::N::O::P::X #boolean evaluation here
end
Case equality (for case/when)
VALUE TO VARIABLE ASSIGNMENT
Definition Calling example Sugared syntax SETTER METHODS
x = 1
def === (x) obj.===(x) obj === x string = “Hello!” Refer to Setter Methods in Classes

GLOBAL VARIABLES
BANG METHODS
Defined with the $ sign
The bang methods are defined with an exclamation '!'. $gvar = “This is a global variable!”

Ruby Cheatbook by rubynerds.blogspot.com


def stir_mix Classes
METHOD ACCESS RULES end
end
Access Rule Who can access CLASS DEFINITION
Public class Ticket
Other objects can access Objects #class definition
Private end
Only instances of object can access GENERIC OBJECT
mthd on itself (self only)
obj = Object.new CLASS OBJECT DEFINITION
Protected Only instances of object can access tix = Ticket.new
mthd on each other OBJECT 'SINGLETON' METHOD DEFINITION
Here's 2 ways to define private/protected/#public methods def obj.method
INSTANCE METHOD DEFINITION
class Ticket
(private example only) puts “instance method definition”
def method
end
method 1: #method definition
Class Bake end
#method call
def bake_cake end
obj.method
add_egg
stir_mix tix = Ticket.new
end DEFAULT OBJECT METHODS #This is how instance methods are called
tix.method
def add_egg respond_to?
end Checks if methods by the name in argument are defined for CLASS METHOD DEFINITION
def stir_mix the object class Ticket
end obj.respond_to?(“method1”) #This is a class definition
def Ticket.cheapest(*tickets)
#private definition #Class method definition
send
private :add_egg, stir_mix end
end Sends its arguments as 'message' to object (for method end
call)
method 2: x = “method1” INSTANCE VARIABLES
Class Bake obj.send(x)
def bake_cake Defined with @ in front
@venue = “City”
add_egg object_id
stir_mix
Returns specific id of object
end
obj.object_id CLASS/OBJECT INITIALIZATION
private class Ticket
def initialize(venue)
def add_egg methods
end @venue = venue
Returns a list of methods defined for the object end
obj.methods

Ruby Cheatbook by rubynerds.blogspot.com


end #This is how to access them test = Test.new
tix.venue = “city” test.function1
tix = Ticket.new(“City”) tix.cost = 55.90
puts “the ticket price is #{tix.price}” NESTING MODULES/CLASSES
puts “the ticket venue is #{tix.venue}” Nesting can be done like below
SETTER METHODS
Class M
class Ticket
def initialize(venue) ACCESSING CONSTANTS IN CLASSES Module N
Module O
@venue = venue Class Ticket Class P
end Venue = “City” end
end end
#This is the setter method end
def venue=(venue) #This is how it's accessed end
@venue = venue puts Ticket::Venue
end
end To create instance of Class P
INHERITANCE p = M::N::O::P.new
tix = Ticket.new(“Hall”) Inheritance is defined using < at class definition.
#This is how it's called To force absolute paths (search from top of #hierarchy
tix.venue = “Field” Example:
::P.new
Magazine inherits from Publications class
Class Magazine < Publications
ATTR_* METHODS Self
#class definitions
end
Definition Description
WHAT IS SELF AT DIFFERENT LEVELS
attr_writer :variable Defines write method for variable Modules Location What self is
attr_reader :variable Defines read method for variable
MODULE DEFINITION Top level main
attr_accessor :variable Defines read & write methods for module MyModule
#module definition Instance method Instance of object calling the
variable end method
Note: variables are read using the .variable method and USING MODULES Instance method in Instance of class that mixes in
written using the .variable = method. module MyModule
Module Module OR Individual object
def function1
Example end extended by Module
class Ticket end
attr_writer :cost Singleton method The object itself
attr_reader :price class Test
attr_accessor :venue include MyModule
end end SELF AS DEFAULT MESSAGE RECEIVER
Class C
tix = Ticket.new #This is how to call on module functions
def C.x

Ruby Cheatbook by rubynerds.blogspot.com


#method definition puts “x smaller than 10” unless x > 10 n = n + 1
end next unless n>9 #next skips to nxt
loop
x #This is equivalent to self.x CASE STATEMENTS break}
end You can specify more than one condition for each 'when' WHILE STATEMENTS
x = gets
Control Flow case x Equivalent to classic while statement in C
when “y”, “yes” n = 1
#some code while n < 11
IF AND FRIENDS
when “n”, “no” puts n
If #some code n = n + 1
if x > 10 when “c”, “cancel” end
#some code
puts x OR
end else n = 1
#some code n = n + 1 while n < 10
if x > 10 then puts x end end puts "We've reached 10!"

puts x if x > 10 Case matching can be customized for objects by defining Equivalent to classic do-while
the threequal function n = 1
If-else def ===(other_ticket) begin
if x > 10 self.venue == other_ticket.venue puts n
puts x end n = n + 1
else end while n< 11
puts “smaller than 10” #And this is case example for above def
end case ticket1
when ticket2 UNTIL STATEMENTS
If-elsif-else puts "Same venue as ticket2!" Opposite of while
if x > 10 when ticket3 n = 1
puts “x larger than 10” puts "Same venue as ticket3!" until n > 10
elsif x > 7 else puts n
puts “7 < x < 10” puts "No match" n = n + 1
elsif x > 5 end end
puts “5 < x < 7”
Or
else
LOOP STATEMENTS n = 1
puts “smaller than 5”
n = 1 n = n + 1 until n == 10
end
loop do puts "We've reached 10!"
n = n + 1
Unless – evaluates the opposite way as if break if n > 9
unless x > 10 FOR STATEMENTS
end
puts “x smaller than 10”
Or For every value in array
end celsius = [0, 10, 20, 30, 40, 50, 60]
n = 1
loop {

Ruby Cheatbook by rubynerds.blogspot.com


for c in celsius
puts "c\t#{Temperature.c2f(c)}" CREATING EXCEPTION CLASSES
end EACH STATEMENT class MyNewException < Exception
[1,2,3,4,5].each {|x| puts x * 10} end
YIELD STATEMENTS / ITERATOR
Or
raise MyNewException
Yield without arguments [1,2,3,4,5].each do |x| puts x * 10 end
def demo_of_yield
puts "Executing the method body..."
Exception Handling PART 2
puts "Yield control to the block..."
yield
puts "Back from the block—finished!" RESCUE
end
Built – Ins
Begin/end wrapped method
demo_of_yield { puts "Now in block!”}
print “Enter a number:” BUILT-IN CONVERSION METHODS
n = gets.to_i
begin to_s #to string
result = 100/n to_i #to integer
Yield with arguments to_a #to array
def yield_an_arg rescue
puts “your number didn't work” to_f #to float
puts "Yielding 10!"
yield(10) exit These methods are defined by default for most objects.
end
end However, you can also define them for your objects using
#argument sent to block thru |x| puts result
the standard def statement.
yield_an_arg {|x| puts "#{x}" }
For specific rescue, add Exception name
rescue ZeroDivisionError
Block returns argument BUILT-IN EQUALITY TESTS
def return_yielding
puts "code block will do by 10." Rescue in method definition Apart from the usual comparison operators, the following
result = yield(3) def multiply(x) methods are also built-in for most objects.
puts "The result is #{result}." result = 100/x obj.eql?
end puts result obj.equal?
return_yielding {|x| x * 10 } rescue ZeroDivisionError #begin x needed
puts “wrong value!”
exit COMPARABLE
Iteration within blocks
def temp(temps) end class Bid
for temp in temps include Comparable
attr_accessor :contractor
converted = yield(temp) RAISE attr_accessor :quote
puts
def reraiser(x)
"#{temp}\t#{converted}"
result = 100/x #This is called the spaceship
end
rescue ZeroDivisionError => e #operator – must always return -1, 1,
end
puts “Division by Zero!” #or 0
raise e def <=>(other_bid)
cels = [0,10,20,30,40,50,60,70]
end if self.quote < other_bid.quote
temp(cels) {|cel| cel * 9 / 5 + 32 }
-1

Ruby Cheatbook by rubynerds.blogspot.com


elsif self.quote > puts str << ”There”#output: Hi There
other_bid.quote puts str #output: Hi There puts str[1,2] = “ge” #output: age
1
else
0 REPLACING A STRING'S CONTENTS STRING COMPARISONS
end str = “Hi There” “a” == “a”
end puts str #output: Hi There “a”.eql?(“a”)
end str.replace(“Goodbye”) This function checks if the two strings are equal objects
puts str #output: Goodbye “a”.equal?(“a”)
Once this function is defined, use it by using the usual Larger than or less than comparisons compare ASCII
less_than, larger_than or equal_to operators MASSAGING STRINGS
values of the characters in a string
a < b str = “ruby” “a” < “b” #output: true
a > b str.capitalize #output: “Ruby” “a” < “A” #output: true
a == b str.reverse #output: “ybur”
str.upcase #output: “RUBY”
Strings and Symbols SYMBOLS
str = “RUBY”
str.downcase #output: “ruby” only one symbol object can exist for any given unit of text
STRING QUOTING MECHANISM :a
str = “Ruby” :venue
Token Example str.swapcase #output: “rUBY” “a”.to_sym
' ' 'You\'ll have to “escape” single str.chop #output: “Rub” “a”.intern
quotes'
str = “ Ruby “
“ “ “You'll have to \”escape\” double str.strip #output: “Ruby” UNIQUENESS OF SYMBOLS
quotes” str.lstrip #output: “Ruby ” :a.equal?(:a) #output: true
%q %q{'Single quoted' example – no str.rstrip #output: “ Ruby”
escape}
str = “Ruby\n” RAILS STYLE METHOD ARGUMENTS
%Q %Q{“Double quoted” example – no str.chomp #output: “Ruby” <%= link_to "Click here",
escape} :controller => "book",
:action => "show",
STRUNG GET/SET METHODS :id => book.id %>
COMBINING STRINGS Getter methods ( [ ] )
“a” + “b” + “c” str = “abc” Numerical Objects
puts str[2] #output:99 (ASCII value c)
str = “Hi ” puts str[2].chr #output: c SENDING MESSAGES TO NUMBERS
puts str + “There” #output: Hi There x=12
puts str #output: Hi puts str[1,2] #output: bc
x.zero?
puts “#{str}There” #output: Hi There Setter methods ( [ ]=) n = 98.6
puts str #output: Hi str = “abc” m = n.round
puts str[2] = “d” #output: abd

Ruby Cheatbook by rubynerds.blogspot.com


Array.new(3) {n +=1; n * 10}
ascii_value = 97.chr t.strftime(“%m-%d-%Y”)
str = 2.ro_s INSERTING, RETRIEVING AND REMOVING
Specifier Description
Inserting
NON-DECIMAL NUMBERS %Y Year (4 digits) a = []
a[0] = 1 #[1]
Hexadecimal integers %y Year (las 2 digits) a[1,2] = 2,3 #[1,2,3]
0x12 #equals 18
%b, %B Short month, full month Retrieving
Octal integers (begin with 0) a # [1,2,3]
012 #equals 10 %m Month (number) a[2] # 3
a[0,2] # [1,2]
%d Day of month (left padded with zeros)
to_i conversion from any base to decimal.
Supply the base to convert from as argument to to_i %e Day of months(left padded with blanks) Special methods for beginnings and ends of arrays
“10”.to_i(17) #result: 17 a = [1,2,3,4]
“12345”.to_i(13) #result: 33519 %a, %A Short day name, full day name a.unshift(0) #[0,1,2,3,4]

%H, %I Hour (24h), hour (12h am/pm) a = [1,2,3,4]


a.push(5,6,7) #[1,2,3,4,5,6,7]
Times and Dates %M Minute Or, if you want to 'push' just one argument,
a = [1,2,3,4]
Manipulated through three classes: %S Second
a << 5 #[1,2,3,4,5]
Date
Time %c Equals “%a %b %d %H:%M:%S %Y”
popd = a.pop #[1,2,3,4]
DateTime puts popd # 5
%x Equals “%m/%d/%y”
'require' the classes into your program to use them shiftd = a.shift #[2,3,4]
puts shiftd # 1
Arrays and Hashes COMBINING ARRAYS
METHODS
a = [1,2,3]
d = Date.today #returns today's date CREATING ARRAYS b = a + [4,5,6] #[1,2,3,4,5,6]
puts d << 2 #rewind date by 2 months
a = Array.new puts a #[1,2,3]
puts d >> 5 #advance date by 5 months
a = [] a.concat{[4,5,6]} #[1,2,3,4,5,6]
a = [1,2, “three”, 4] puts a #[1,2,3,4,5,6]
t = Time.new
t.year a.replace{[4,5,6]} #[4,5,6]
t.month You can initialize Array size and contents using Array.new a.zip{[7,8,9]} #[[4,7],[5,8],[6,9]]
t.day Array.new(3) #output: [nil,nil,nil]
t.hour Array.new(3, “abc”) ARRAY TRANSFORMATIONS
t.min #output: [“abc”, “abc”, “abc”]
a = [0,2,4]
t.sec
b = [1,3,5]
t.usec Array.new can also take code blocks numbers = a.zip(b) #[[0,1],[2,3],[4,5]]
n = 0 numbers = a.zip(b).flatten #[0,1,2,3,4,5]

Ruby Cheatbook by rubynerds.blogspot.com


state_hash.store(“New York”, “NY”)
numbers.reverse #[5,4,3,2,1,0] criteria in code block
puts numbers #[0,1,2,3,4,5] Example:
numbers.!reverse #[5,4,3,2,1,0] RETRIEVING FROM A HASH
[1,2,3,4,5,6,7].find{|n| n > 5}
puts numbers #[5,4,3,2,1,0] state = state_hash[“New York”]
[1,2,3,4,5,6,7].find_all{|n| n > 5}
state = state_hash.fetch(“New York”)
[“abc”,“def”,123].join #”abcdef123” To retrieve values from multiple keys,
[“abc”,“def”,123].join(“, “) ARRAY QUERYING states = state_hash.values_at(“New
#”abc, def, 123” York”, “Delaware”)
Method + Sample call Description
c = [1,2,1,3,4,5,6,4]
h.size
c.uniq #[1,2,3,4,5,6] Returns the number of values in COMBINING HASHES
puts c array h1 = {“Smith => “John”}
#[1,2,1,3,4,5,6,4] h2 = {“Jones” => “Jane”}
c.!uniq #[1,2,3,4,5,6] h.empty? True if array is empty h1.update(h2)
puts c #[1,2,3,4,5,6]
h.include?(item) using the update method, if h2 has a key that is similar to a
True if item is in array
key in h1, then h1's key – value is overwritten
ARRAY ITERATION, FILTERING AND QUERYING h.any?{|item| True if any values in array h3 = h1.merge(h2)
test}
Definition Description passes test in code block using the merge method, the combined hash is assigned to
[].each{|x| #code} Iterates thru array executing h.all?{|item| a third hash and h1 and h2 keeps their contents
True if all values in array
test}
code block to each item in passes test in code block
array
HASH TRANSFORMATIONS
h = {1 => “one”, 2 => “two”}
[].each_with_index Iteratus thru array yielding to CREATING HASHES h.invert #{“two” => 2, “one” => 1}
{|x, index} #code}
code block each item in array h =
{}
h =
Hash.new h.clear #{}
along with its index, then h =
Hash.new(0) #specify a default value h.replace({10=>”ten”,20=>”twenty”})
executing code block h =
Hash[ “Connecticut”=> “CT” #output: {10=>”ten”, 20=>”twenty”}
“Delaware” => “DE”]
[].map{|x| #code} Same as each, but map returns h = { “Connecticut”=> “CT” HASH ITERATION, FILTERING AND QUERYING
“Delaware” => “DE”
an array h.each do |key,value|
“New Jersey” => “NJ”
[].find{} “Virginia” => “VA” ) puts “Word for #{key} is #{value}”
Find first occurrence of criteria end
in code block Note: '=>' can be interchanged with ',' for hashes
To create a hash which sets every non-existent key it gets
[].find_all{} Definition Description
Find all occurences that match
to a default value, use code blocks
criteria in code block h = Hash.new {|hash, key| hash[key] = 0} h.keys Returns all keys in hash
[].reject{} Removes all occurences of ADDING TO A HASH h.values Returns all values in hash
state_hash[“New York”] = “NY”

Ruby Cheatbook by rubynerds.blogspot.com


h.each_key{|k| #code} Yields all keys to code blk class to enable your class to perform the following methods
select You could also do sorting by defining the sort order in a
h.each_value{|v| #code} Yields all values to code bk reject
code block
find year_sort = [ed1,ed2,ed3].sort do |a,b|
h.select{|k, v| k > 10} Returns all key-value pairs map a.year <=> b.year
that meet criteria in code bk. end
Returns an array of two Example:
class Colors
element arrays ["2",1,5,"3",4,"6"].sort do |a,b|
include Enumerable
def each a.to_i <=> b.to_i
h.find_all{|k, v| k > 10} Same as .select end
yield “red”
yield “green”
h.find Finds first key-value pair
yield “blue” the sort_by method helps to sort different types of values
that meet criteria in code bk yield “yellow” by taking in a code block that tells it how to handle different
end
h2 = h.map{|k, v| #code } Returns an array of results end types of values
returned from code bk yield r = Colors.new ["2",1,5,"3",4,"6"].sort_by do |a|
y_color = r.find {|col| col[0,1] == 'y'} a.to_i
puts “First color with y is #{y_color}” end
HASH QUERYING
once each is defined, there are many methods available to Regular Expressions
Method + Sample call Description the class.
h.has_key?(1) Enumerable.instance_methods(false).sort THE REGEX LITERAL CONSTRUCTOR
True is h has the key 1
provides a list of methods available. is a pair of forward slashes : - / /
h.include?(1) Same as has_key?
h.key?(1) Same as has_key? The functions sort and sort_by require the following to be PATTERN MATCHING OPERATION
h.member?(1) done: /abc/.match(“abcdefghi”)
Same as has_key? “abcdefghi”.match(/abc/)
1. Define a comparison method '<=>'
h.has_value? Or
True if any value in h is “three” 2. Place objects in a container, (e.g. Array)
(“three”) “abcdefghi” =~ /abc/
Example: /abc/ =~ “abcdefghi”
h.value(“three”) Same as has_value? Class Edition
etc... Note: match returns MatchData, while =~ returns index of
h.empty? True if h is empty def <=>(other_edition) character in string where match started
h.size self.price <=>
Number of key/value pairs in h other_edition.price
end
end
THE ENUMERABLE MODULE
Include Enumerable and define an each method for your price_sort = [ed1,ed2,ed3,ed4,ed5].sort

Ruby Cheatbook by rubynerds.blogspot.com


BUILDING A REGEX PATTERN ?! /\d+(?!\.)/ Negative Lookahead Regex modifiers

Literal characters assertion Notation Usage example Description


Digits, alphabets, whitespaces, underscores etc. Special escape sequences i /abc/i Case-insensitive mod
/abc/
/019/ Notation Usage example Description m /\(.*?\)/m Multiline modifier
\d /\d/ Match any digit
Special characters
\D /\D/ Match other than digit Wildcard character '.' (dot)
Need to be preceded by '\' to be included as a matching
/.ejected/ #matches rejected & dejected
pattern \w /\w/ Match any digit, alphabet,
^, $, ?, ., /, \, [, ], {, }, (, ), +, *
and underscore Character classes (in [ ])
Notation Usage example Description /[dr]ejected/ #matches d or r +ejected
\W /\W/ Match other than digit,
. /.ejected/ Wildcard character
alphabet, and underscore /[a-z]/ #matches any lowercase letter
/ // Regex literal constructor \s /\s/ Match any whitespace /[A-Fa-f0-9]/ #matches any hexadecimal
\ / \? / digit
Escape character character
[ ] /[a-z]/ \S /\S/ Lookahead assertions
Character class Match any non-
{ } /\d{3}-\d{4}/ Number/Range of whitespace character To match numbers only if it ends with a period,
/\d{1,10}/ str = "123 456. 789"
Repetition character Regex anchors m = /\d+(?=\.)/.match(str)
( ) /([A-Z]\d) Notation Usage example Description
Atom character
{5}/ Strings and regex interchangeability
^ /^\s*#\ Beginning of line anchor
^ /[^a-z]/ String to regex
Negative character (in $ /\.$/ str = “def”
End of line anchor
character classes) /abc#{str}/
\A /\AFour
? /Mrs?/ Beginning of string
Zero or One character score/ str = “a.c”
re = /#{Regexp.escape(str)}/ # = /a\.c/
+ /\d+/ \z /earth.\z/
One or More character End of string
* /\d*/ \Z /earth.\Z/ From regex to string
Zero or More character End of string (except for
puts /abc/ #output: (?-mix:abc)
+? / *? /\d+?/ or final newline) p /abc/ #output: /abc/
Non-greedy One or More /
/\d*?/ \b /\b\w+\b/
Zero or More Word boundary ex.” !!!
?= /\d+(?=\.)/ word***” (matches
Lookahead assertion
“word”)

Ruby Cheatbook by rubynerds.blogspot.com


MATCHDATA AND GLOBAL VARIABLES m.pre_match Returns part of string before String#sub/sub!/gsub/gsub!
match sub and gsub are methods for changing the contents of
When a regex matching is performed with parenthetical
strings in Ruby. Gsub makes changes throughout a string,
groupings: m.post_match Returns part of string after
/([A-Za-z]+), [A-Za-z]+(Mrs?\.)/ while sun makes at most one substitution. Bang
.match(str) match
equivalents modify its receivers.
the results of the match (submatches), if any was found, is: m.begin(index) Returns the position of 1
st

1) Ruby populates a series of global variables to character matched in submatch sub


access those matches referenced by index “typigraphical error”.sub(/i/, “o”)
2) Returned in the form of MatchData Or using code blocks,
m.end(index) Returns the position of last “capitalize the first vowel”.
Note: if no match found, match returns nil
character matched in sub([aeiou]/){|s| s.upcase}
submatche referenced by index
Global variables gsub
Are populated by order of matches according to numbers. “capitalize every word”.gsub(/\b\w/)
{|s| s.upcase}
First match, $1, second, $2 etc: METHODS THAT USE REGEX
$1, $2, $3
String#scan Using sub and gsub captures in replacement string, using
Example use
scan goes from left to right thru a string, looking for a match \1, \2, \3 etc:
puts “1st match:#{$1} & 2nd:#{2}”
for the pattern specified. Results are returned in an array. “aDvid”.sub(/([a-z])([A-Z]), '\2\1')
“testing 1 2 3 testing 4 5 6”.scan(/\d/)
MatchData
string = “My number is (123) 555-1234.” returns the array: grep
pattern =/\((\d{3})\)\s+(\d{3})-(\d{4})/ [“1”, “2”, “3”, “4”, “5”, “6”] grep does a select operation on an array based on a regex
m = pattern.match(string) if regex is parenthetically grouped, then scan returns an argument.
array of arrays. [“USA”, “UK”, “France”, “Germany”].
grep(/[a-z]/)
Method + Sample call Description grep can also take code blocks
String#split ["USA", "UK", "France", "Germany"].
m.string Split splits a string into multiple substrings and returns them
Returns the entire string grep(/[a-z]/) {|c|
c.upcase }
matched in an array. Split can take a regex or a regular string as
m.captures(index) argument
Returns the submatch “Ruby”.split(//)
referenced by index (start from
0) line =
"first=david;last=black;country=usa"
m[0] record = line.split(/=|;/)
Entire match
m[1],m[2],etc Same as captures (start from 1)

Ruby Cheatbook by rubynerds.blogspot.com


Ruby Dynamics p self #output: main def call_some_proc(pr)
a = [] a = "irrelevant 'a' in method scope"
a.instance_eval(p self) #output: [] puts a
SINGLETON CLASSES pr.call
This method is useful for obtaining acces to another
To get inside the definition body of a singleton class, end
object's private data.
class << object
class C a = "'a' to be used in Proc block"
#method and constant definitions
def initialize pr = Proc.new { puts a }
end
@x = 1 pr.call
Class methods can be defined this way within the body of end call_some_proc(pr)
the class definition: end
class Ticket The output for the above is as follows:
class << self c = C.new
c.instance_eval {puts @x} 'a' to be used in Proc block
#method and constant definition irrelevant 'a' in method scope
end 'a' to be used in Proc block
etc... class_eval (a.k.a module_eval)
end
This method puts you inside a class definition body Proc objects can take arguments
var = “var” pr = Proc.new {|x| p x}
THE EVAL FAMILY OF METHODS class C pr.call(100)
puts var #returns NameError
eval end
If Proc takes more than one argument, extra arguments on
eval executes the string given to it.
Eval(“2+2”) C.class_eval {puts var} #returns “var” either side of the transaction are ignored
pr = Proc.new{|x,y,z| p x,y,z}
pr.call(1,2)
eval lets you, for example, allow program users to give a To define an instance method using an outer-scope
#output: 1
method their own name variable with class_eval, use the define_method method. # 2
print "Method name: " C.class_eval { define_method("talk") # nil
m = gets.chomp { puts var }} pr.call(1,2,3,4)
eval("def #{m}; puts 'Hi!'; end") #output: 1
eval(m) # 2
CALLABLE OBJECTS
# 3
whenever the code is run and user types in a name, a
Proc objects
method by that name is then created.
Proc objects are closures. a Proc object is created with a lambda
Note: the code above lets users in on program definition.
code block that isn't executed until the Proc object is called lambda creates an anonymous function
Given the right commands, eval lets users hack into your
with the call method lam = lambda{puts “A lambda!”}
program, and even system. pr = Proc.new {puts “Proc code block”} lam.call #output: “A lambda!”
pr.call #output: “Proc code block”
instance_eval lambda is a subclass of Proc. The difference from Proc is
Proc objects are closures – it retains the scope from where lambda returns from lambda, Proc returns from the method
Evaluates string or code block given to it, changing self to
it is originally created it's encapsulated in.
be the receiver of instance_eval

Ruby Cheatbook by rubynerds.blogspot.com


puts "No method called #{m} -- class C
Convert code blocks into Proc objects
please try again." def self.const_missing(const)
Done by capturing the blocks in a variable using &. end puts "#{const} is undefined—setting
def grab_block(&block) end it to 1."
block.call C.new.anything const_set(const,1)
end end
end
grab_block { puts "in '&block'" } Module#included
puts C::A
You can also convert a Proc/lambda object to a code block If defined for a module, executes the method whenever puts C::A
using & module is mixed in (included) in a class
lam = lambda {puts "lambda code block"} module M
grab_block &lam def self.included(c) OVERRIDING AND ADDING TO CORE FUNCTIONALITY
puts "I have been mixed into
#{c}." Ruby's core functionality can always be redefined easily
Methods as objects end class Array
methods objects can be obtained using the 'method' end def shuffle
sort_by { rand }
method class C end
class C include M end
def talk end
puts "self is #{self}." Note: be careful, as you may cause problems if your
end program is shared with other developers.
end Class#inherited
c = C.new If defined for a class, executes the method whenever class
meth = c.method(:talk)
meth.call is inherited by another class(subclass).
#output: self is #<C> class C
def self.inherited(subclass)
by default, self is the class where method is defined. To puts "#{self} just got subclassed
unbind self and bind to another object, use unbind and bind by #{subclass}"
end
method. This can only be done if the other object is the end
same class or subclass of the original object.
class D < C class D < C
end end
d = D.new Note: inherited functions are inherited by its subclasses.
unbound = meth.unbind
unbound.bind(d).call Subclasses of the subclasse will also trigger inherited.

CALLBACKS AND HOOKS Module#const_missing


method_missing This method, if defined, is executed whenever an
class C unidentifiable constant is referred to inside a given module
def method_missing(m)
or class.

Ruby Cheatbook by rubynerds.blogspot.com

You might also like