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

Ruby Cheatbook

  • Upload
    asyraf

  • View
    2.811

  • Download
    1

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Ruby Cheatbook

Part 1

The Basics

ARITHMETIC2 + 32 – 32 * 32 / 3

PRINTING TO THE SCREENputs “Hello”print “Hello”p “Hello”

x = “Hello”puts xprint xp x

GETTING INPUT FROM THE SCREENgetsstring = gets

STRING TO NUMBER CONVERSIONx = “100”.to_i

string = “100”x = string.to_i

NUMBER TO STRING CONVERSIONx = 100.to_sx = 100string = x.to_s

COMPARING TWO VALUESx == y

COMMENTING#This is a comment!

FILE HANDLING

File writingfh = File.new(“filename.dat”, “w”)fh.puts x #x is imaginary variable herefh.close

File readingfh = File.read(“filename.dat”)

EXTERNAL CODE INCLUSIONrequire “filename.rb”

Orload “filename.rb”

STRING INTERPOLATIONx=1puts “x is equal to: #{x}”

EMBEDDED RUBY

To embed Ruby code in HTML<%#Ruby code in here%>

To 'print out' result of execution in HTML<%=#Ruby code in here%>

CODE BLOCKS

Any code defined within {} or do end{#code}

ORdo

#code hereend

LITERAL CONSTRUCTORS

Type Constructor Example

String “” or '' “abc” or 'abc'

Symbol : :symbol or :”symbol with spaces”

Array [] [1,2,3,4,5]

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

Range .. or ... 0..10 or 0...10

Regexp // /([a-z]+)/

SYNTACTIC SUGAR

ArithmeticDefinition Calling example Sugared syntaxdef + (x) obj.+(x) obj + x

def – (x) obj.–(x) obj – x

def * (x) obj.*(x) obj * x

def / (x) obj./(x) obj / x

def % (x) obj.%(x) obj % x

Ruby Cheatbook by rubynerds.blogspot.com

Ruby CheatbookBased on Ruby for Railsby David Black

Compiled by Asyraf. rubynerds.blogspot.com

Page 2: Ruby Cheatbook

IncrementalsSugared syntax How ruby sees itx += 1 x = x + 1

x –= 1 x = x – 1

x *= 2 x = x * 2

x /= 2 x = x / 2

x %= 2 x = x % 2

Get/Set/Append dataDefinition Calling example Sugared syntaxdef [](x) obj.[](x) obj [ x]

def []= (x,y) obj.[]=(x,y) obj [ x]= y

def << (x) obj.<<(x) obj << x

Comparison methodDefinition Calling example Sugared syntaxdef ==(x) obj.==(x) obj == x

def > (x) obj.>(x) obj > x

def < (x) obj.<(x) obj < x

def >= (x) obj.>=(x) obj >= x

def <= (x) obj.<=(x) obj <= x

Case equality (for case/when)Definition Calling example Sugared syntaxdef === (x) obj.===(x) obj === x

BANG METHODS

The bang methods are defined with an exclamation '!'.

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: HELLOputs str #output: hello

puts str.upcase!#output: HELLOputs str #output: HELLO

Variables and Constants

CONSTANTS

Constants start with a capital letterConstant = “Hi!”

CONSTANT RESOLUTION IN NESTED CLASSES/MODULESClass M

Module NClass O

Class PX = 1

endend

endend

The constant is accessed byputs M::N::O::P::X

VALUE TO VARIABLE ASSIGNMENTx = 1string = “Hello!”

GLOBAL VARIABLES

Defined with the $ sign$gvar = “This is a global variable!”

INSTANCE VARIABLES

Refer to Instance Variables in Classes

Methods

METHOD DEFINITIONdef method1(x)

value = x + 1return value

end

METHOD ARGUMENTS

Definition Descriptiondef method(a,b,c) Fixed number of argumentsdef method(*a) Variable number of argsdef method(a=1,b=2) Default value for argumentsdef method(a,b=1,*c) Combination arguments

NOTE: def method(a, *b, c) is not allowed! Arguments with * must always be at the end of the argument definition

BOOLEAN METHODSdef ticket.available?

#boolean evaluation hereend

SETTER METHODS

Refer to Setter Methods in Classes

Ruby Cheatbook by rubynerds.blogspot.com

Page 3: Ruby Cheatbook

METHOD ACCESS RULES

Access Rule Who can accessPublic Other objects can accessPrivate Only instances of object can access

mthd on itself (self only)Protected Only instances of object can access

mthd on each otherHere's 2 ways to define private/protected/#public methods (private example only)method 1:

Class Bakedef bake_cake

add_eggstir_mix

end

def add_eggend

def stir_mixend

#private definitionprivate :add_egg, stir_mix

end

method 2:Class Bake

def bake_cakeadd_eggstir_mix

end

privatedef add_eggend

def stir_mixend

end

Objects

GENERIC OBJECT

obj = Object.new

OBJECT 'SINGLETON' METHOD DEFINITION

def obj.methodputs “instance method definition”

end

#method callobj.method

DEFAULT OBJECT METHODS

respond_to? Checks if methods by the name in argument are defined for the object

obj.respond_to?(“method1”)

send Sends its arguments as 'message' to object (for method call)

x = “method1”obj.send(x)

object_id Returns specific id of object

obj.object_id

methodsReturns a list of methods defined for the object

obj.methods

Classes

CLASS DEFINITIONclass Ticket

#class definitionend

CLASS OBJECT DEFINITIONtix = Ticket.new

INSTANCE METHOD DEFINITIONclass Ticket

def method#method definition

endend

tix = Ticket.new#This is how instance methods are calledtix.method

CLASS METHOD DEFINITIONclass Ticket

#This is a class definitiondef Ticket.cheapest(*tickets)

#Class method definitionend

end

INSTANCE VARIABLES

Defined with @ in front@venue = “City”

CLASS/OBJECT INITIALIZATIONclass Ticket

def initialize(venue)@venue = venue

end

Ruby Cheatbook by rubynerds.blogspot.com

Page 4: Ruby Cheatbook

end

tix = Ticket.new(“City”)

SETTER METHODSclass Ticket

def initialize(venue)@venue = venue

end

#This is the setter methoddef venue=(venue)

@venue = venueend

end

tix = Ticket.new(“Hall”)#This is how it's calledtix.venue = “Field”

ATTR_* METHODS

Definition Description

attr_writer :variable Defines write method for variable

attr_reader :variable Defines read method for variable

attr_accessor :variable Defines read & write methods for variable

Note: variables are read using the .variable method and written using the .variable = method.

Exampleclass Ticket

attr_writer :costattr_reader :priceattr_accessor :venue

end

tix = Ticket.new

#This is how to access themtix.venue = “city”tix.cost = 55.90puts “the ticket price is #{tix.price}”puts “the ticket venue is #{tix.venue}”

ACCESSING CONSTANTS IN CLASSESClass Ticket

Venue = “City”end

#This is how it's accessedputs Ticket::Venue

INHERITANCE

Inheritance is defined using < at class definition.Example:Magazine inherits from Publications class

Class Magazine < Publications#class definitions

end

Modules

MODULE DEFINITIONmodule MyModule

#module definitionend

USING MODULESmodule MyModuledef function1endend

class Testinclude MyModuleend

#This is how to call on module functions

test = Test.newtest.function1

NESTING MODULES/CLASSES

Nesting can be done like belowClass M

Module NModule O

Class Pend

endend

end

To create instance of Class Pp = M::N::O::P.new

To force absolute paths (search from top of #hierarchy::P.new

Self

WHAT IS SELF AT DIFFERENT LEVELS

Location What self is

Top level main

Instance method Instance of object calling the method

Instance method in Module

Instance of class that mixes in Module OR Individual object extended by Module

Singleton method The object itself

SELF AS DEFAULT MESSAGE RECEIVERClass C

def C.x

Ruby Cheatbook by rubynerds.blogspot.com

Page 5: Ruby Cheatbook

#method definitionend

x #This is equivalent to self.xend

Control Flow

IF AND FRIENDS

If if x > 10

puts xend

if x > 10 then puts x end

puts x if x > 10

If-elseif x > 10

puts xelse

puts “smaller than 10”end

If-elsif-elseif x > 10

puts “x larger than 10”elsif x > 7

puts “7 < x < 10”elsif x > 5

puts “5 < x < 7”else

puts “smaller than 5”end

Unless evaluates the opposite way as if–unless x > 10

puts “x smaller than 10”end

puts “x smaller than 10” unless x > 10

CASE STATEMENTS

You can specify more than one condition for each 'when'x = getscase x

when “y”, “yes”#some code

when “n”, “no”#some code

when “c”, “cancel”#some code

else#some code

end

Case matching can be customized for objects by defining the threequal function

def ===(other_ticket)self.venue == other_ticket.venue

end

#And this is case example for above defcase ticket1 when ticket2 puts "Same venue as ticket2!" when ticket3 puts "Same venue as ticket3!" else puts "No match" end

LOOP STATEMENTSn = 1loop do

n = n + 1break if n > 9

end

Orn = 1loop {

n = n + 1next unless n>9 #next skips to nxt

loopbreak}

WHILE STATEMENTS

Equivalent to classic while statement in Cn = 1while n < 11

puts nn = n + 1

end

ORn = 1 n = n + 1 while n < 10 puts "We've reached 10!"

Equivalent to classic do-whilen = 1begin

puts nn = n + 1

end while n< 11

UNTIL STATEMENTS

Opposite of whilen = 1 until n > 10 puts n n = n + 1 end

Orn = 1 n = n + 1 until n == 10 puts "We've reached 10!"

FOR STATEMENTS

For every value in array celsius = [0, 10, 20, 30, 40, 50, 60]

Ruby Cheatbook by rubynerds.blogspot.com

Page 6: Ruby Cheatbook

for c in celsius puts "c\t#{Temperature.c2f(c)}" end

YIELD STATEMENTS / ITERATOR

Yield without argumentsdef demo_of_yield puts "Executing the method body..." puts "Yield control to the block..." yield puts "Back from the block—finished!" end demo_of_yield { puts "Now in block!”}

Yield with argumentsdef yield_an_arg puts "Yielding 10!" yield(10) end #argument sent to block thru |x|yield_an_arg {|x| puts "#{x}" }

Block returns argumentdef return_yielding puts "code block will do by 10." result = yield(3) puts "The result is #{result}." end return_yielding {|x| x * 10 }

Iteration within blocksdef temp(temps) for temp in temps converted = yield(temp) puts "#{temp}\t#{converted}" end end

cels = [0,10,20,30,40,50,60,70] temp(cels) {|cel| cel * 9 / 5 + 32 }

EACH STATEMENT[1,2,3,4,5].each {|x| puts x * 10}

Or[1,2,3,4,5].each do |x| puts x * 10 end

Exception Handling

RESCUE

Begin/end wrapped methodprint “Enter a number:”n = gets.to_ibegin

result = 100/nrescue

puts “your number didn't work”exit

endputs result

For specific rescue, add Exception namerescue ZeroDivisionError

Rescue in method definitiondef multiply(x)

result = 100/xputs result

rescue ZeroDivisionError #begin x neededputs “wrong value!”exit

end

RAISEdef reraiser(x)

result = 100/xrescue ZeroDivisionError => e

puts “Division by Zero!”raise e

end

CREATING EXCEPTION CLASSESclass MyNewException < Exceptionend

raise MyNewException

PART 2

Built – Ins

BUILT-IN CONVERSION METHODSto_s #to stringto_i #to integerto_a #to arrayto_f #to float

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

BUILT-IN EQUALITY TESTS

Apart from the usual comparison operators, the following methods are also built-in for most objects.

obj.eql?obj.equal?

COMPARABLEclass Bid

include Comparableattr_accessor :contractorattr_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

Ruby Cheatbook by rubynerds.blogspot.com

Page 7: Ruby Cheatbook

elsif self.quote > other_bid.quote

1else

0end

endend

Once this function is defined, use it by using the usual less_than, larger_than or equal_to operators

a < ba > ba == b

Strings and Symbols

STRING QUOTING MECHANISM

Token Example' ' 'You\'ll have to “escape” single

quotes'

“ “ “You'll have to \”escape\” double quotes”

%q %q{'Single quoted' example – no escape}

%Q %Q{“Double quoted” example – no escape}

COMBINING STRINGS“a” + “b” + “c”

str = “Hi ”puts str + “There” #output: Hi Thereputs str #output: Hi

puts “#{str}There” #output: Hi Thereputs str #output: Hi

puts str << ”There”#output: Hi Thereputs str #output: Hi There

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

MASSAGING STRINGSstr = “ruby”str.capitalize #output: “Ruby”str.reverse #output: “ybur”str.upcase #output: “RUBY”

str = “RUBY”str.downcase #output: “ruby”

str = “Ruby”str.swapcase #output: “rUBY”str.chop #output: “Rub”

str = “ Ruby “str.strip #output: “Ruby”str.lstrip #output: “Ruby ”str.rstrip #output: “ Ruby”

str = “Ruby\n”str.chomp #output: “Ruby”

STRUNG GET/SET METHODS

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

STRING COMPARISONS“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

SYMBOLS

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

UNIQUENESS OF SYMBOLS:a.equal?(:a) #output: true

RAILS STYLE METHOD ARGUMENTS<%= link_to "Click here",

:controller => "book", :action => "show", :id => book.id %>

Numerical Objects

SENDING MESSAGES TO NUMBERSx=12x.zero?

n = 98.6m = n.round

Ruby Cheatbook by rubynerds.blogspot.com

Page 8: Ruby Cheatbook

ascii_value = 97.chrstr = 2.ro_s

NON-DECIMAL NUMBERS

Hexadecimal integers0x12 #equals 18

Octal integers (begin with 0)012 #equals 10

to_i conversion from any base to decimal. Supply the base to convert from as argument to to_i

“10”.to_i(17) #result: 17“12345”.to_i(13) #result: 33519

Times and Dates

Manipulated through three classes:DateTime DateTime

'require' the classes into your program to use them

METHODSd = Date.today #returns today's dateputs d << 2 #rewind date by 2 monthsputs d >> 5 #advance date by 5 months

t = Time.newt.yeart.montht.dayt.hourt.mint.sect.usec

t.strftime(“%m-%d-%Y”)

Specifier Description

%Y Year (4 digits)

%y Year (las 2 digits)

%b, %B Short month, full month

%m Month (number)

%d Day of month (left padded with zeros)

%e Day of months(left padded with blanks)

%a, %A Short day name, full day name

%H, %I Hour (24h), hour (12h am/pm)

%M Minute

%S Second

%c Equals %a %b %d %H:%M:%S %Y“ ”

%x Equals %m/%d/%y“ ”

Arrays and Hashes

CREATING ARRAYSa = Array.newa = []a = [1,2, “three”, 4]

You can initialize Array size and contents using Array.newArray.new(3) #output: [nil,nil,nil]Array.new(3, “abc”) #output: [“abc”, “abc”, “abc”]

Array.new can also take code blocksn = 0

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

INSERTING, RETRIEVING AND REMOVING Inserting

a = []a[0] = 1 #[1]a[1,2] = 2,3 #[1,2,3]

Retrievinga # [1,2,3]a[2] # 3a[0,2] # [1,2]

Special methods for beginnings and ends of arraysa = [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]

Or, if you want to 'push' just one argument, a = [1,2,3,4]a << 5 #[1,2,3,4,5]

popd = a.pop #[1,2,3,4]puts popd # 5shiftd = a.shift #[2,3,4]puts shiftd # 1

COMBINING ARRAYSa = [1,2,3]b = a + [4,5,6] #[1,2,3,4,5,6]puts a #[1,2,3]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]a.zip{[7,8,9]} #[[4,7],[5,8],[6,9]]

ARRAY TRANSFORMATIONSa = [0,2,4]b = [1,3,5]numbers = a.zip(b) #[[0,1],[2,3],[4,5]]numbers = a.zip(b).flatten#[0,1,2,3,4,5]

Ruby Cheatbook by rubynerds.blogspot.com

Page 9: Ruby Cheatbook

numbers.reverse #[5,4,3,2,1,0]puts numbers #[0,1,2,3,4,5]numbers.!reverse #[5,4,3,2,1,0]puts numbers #[5,4,3,2,1,0]

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

#”abc, def, 123”

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]c.!uniq #[1,2,3,4,5,6]puts c #[1,2,3,4,5,6]

ARRAY ITERATION, FILTERING AND QUERYING

Definition Description[].each{|x| #code} Iterates thru array executing

code block to each item in array

[].each_with_index {|x, index} #code}

Iteratus thru array yielding to code block each item in array along with its index, then executing code block

[].map{|x| #code} Same as each, but map returns an array

[].find{} Find first occurrence of criteria in code block

[].find_all{} Find all occurences that match criteria in code block

[].reject{} Removes all occurences of

criteria in code blockExample:

[1,2,3,4,5,6,7].find{|n| n > 5}[1,2,3,4,5,6,7].find_all{|n| n > 5}

ARRAY QUERYING

Method + Sample call Descriptionh.size Returns the number of values in

arrayh.empty? True if array is emptyh.include?(item) True if item is in arrayh.any?{|item| test}

True if any values in array passes test in code block

h.all?{|item| test}

True if all values in array passes test in code block

CREATING HASHESh = {}h = Hash.newh = Hash.new(0) #specify a default valueh = Hash[ “Connecticut”=> “CT”

“Delaware” => “DE”]h = { “Connecticut”=> “CT”

“Delaware” => “DE”“New Jersey” => “NJ”“Virginia” => “VA” )

Note: '=>' can be interchanged with ',' for hashesTo 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}

ADDING TO A HASHstate_hash[“New York”] = “NY”

state_hash.store(“New York”, “NY”)

RETRIEVING FROM A HASHstate = state_hash[“New York”]state = state_hash.fetch(“New York”)

To retrieve values from multiple keys,states = state_hash.values_at(“New

York”, “Delaware”)

COMBINING HASHESh1 = {“Smith => “John”}h2 = {“Jones” => “Jane”}h1.update(h2)

using the update method, if h2 has a key that is similar to a key in h1, then h1's key value is overwritten–

h3 = h1.merge(h2)

using the merge method, the combined hash is assigned to a third hash and h1 and h2 keeps their contents

HASH TRANSFORMATIONSh = {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 QUERYINGh.each do |key,value|

puts “Word for #{key} is #{value}”end

Definition Description

h.keys Returns all keys in hash

h.values Returns all values in hash

Ruby Cheatbook by rubynerds.blogspot.com

Page 10: Ruby Cheatbook

h.each_key{|k| #code} Yields all keys to code blk

h.each_value{|v| #code} Yields all values to code bk

h.select{|k, v| k > 10} Returns all key-value pairs that meet criteria in code bk. Returns an array of two element arrays

h.find_all{|k, v| k > 10} Same as .select

h.find Finds first key-value pair that meet criteria in code bk

h2 = h.map{|k, v| #code } Returns an array of results returned from code bk yield

HASH QUERYING

Method + Sample call Descriptionh.has_key?(1) True is h has the key 1h.include?(1) Same as has_key?h.key?(1) Same as has_key?h.member?(1) Same as has_key?h.has_value?(“three”)

True if any value in h is three“ ”

h.value(“three”) Same as has_value?h.empty? True if h is emptyh.size Number of key/value pairs in h

THE ENUMERABLE MODULE

Include Enumerable and define an each method for your

class to enable your class to perform the following methodsselectrejectfindmap

Example:class Colors

include Enumerabledef each

yield “red”yield “green”yield “blue”yield “yellow”

endendr = Colors.newy_color = r.find {|col| col[0,1] == 'y'}puts “First color with y is #{y_color}”

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. Define a comparison method '<=>'2. Place objects in a container, (e.g. Array)

Example:Class Editionetc...

def <=>(other_edition) self.price <=>

other_edition.price end

end

price_sort = [ed1,ed2,ed3,ed4,ed5].sort

You could also do sorting by defining the sort order in a code block

year_sort = [ed1,ed2,ed3].sort do |a,b| a.year <=> b.year end

["2",1,5,"3",4,"6"].sort do |a,b| a.to_i <=> b.to_i

end

the sort_by method helps to sort different types of values by taking in a code block that tells it how to handle different types of values

["2",1,5,"3",4,"6"].sort_by do |a| a.to_i

end

Regular Expressions

THE REGEX LITERAL CONSTRUCTOR

is a pair of forward slashes : - / /

PATTERN MATCHING OPERATION/abc/.match(“abcdefghi”)“abcdefghi”.match(/abc/)

Or“abcdefghi” =~ /abc//abc/ =~ “abcdefghi”

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

Ruby Cheatbook by rubynerds.blogspot.com

Page 11: Ruby Cheatbook

BUILDING A REGEX PATTERN

Literal charactersDigits, alphabets, whitespaces, underscores etc.

/abc//019/

Special characters Need to be preceded by '\' to be included as a matching pattern

^, $, ?, ., /, \, [, ], {, }, (, ), +, *

Notation Usage example Description. /.ejected/ Wildcard character/ // Regex literal constructor\ / \? / Escape character [ ] /[a-z]/ Character class{ } /\d{3}-\d{4}/

/\d{1,10}/Number/Range of Repetition character

( ) /([A-Z]\d){5}/

Atom character

^ /[^a-z]/ Negative character (in character classes)

? /Mrs?/ Zero or One character+ /\d+/ One or More character* /\d*/ Zero or More character+? / *? /\d+?/ or

/\d*?/Non-greedy One or More / Zero or More

?= /\d+(?=\.)/ Lookahead assertion

?! /\d+(?!\.)/ Negative Lookahead assertion

Special escape sequencesNotation Usage example Description\d /\d/ Match any digit\D /\D/ Match other than digit\w /\w/ Match any digit, alphabet,

and underscore\W /\W/ Match other than digit,

alphabet, and underscore\s /\s/ Match any whitespace

character\S /\S/ Match any non-

whitespace characterRegex anchorsNotation Usage example Description^ /^\s*#\ Beginning of line anchor$ /\.$/ End of line anchor\A /\AFour

score/Beginning of string

\z /earth.\z/ End of string\Z /earth.\Z/ End of string (except for

final newline)\b /\b\w+\b/ Word boundary ex. ” ! !!

word*** (matches” word )“ ”

Regex modifiersNotation Usage example Descriptioni /abc/i Case-insensitive modm /\(.*?\)/m Multiline modifier

Wildcard character '.' (dot)/.ejected/ #matches rejected & dejected

Character classes (in [ ])/[dr]ejected/ #matches d or r +ejected

/[a-z]/ #matches any lowercase letter

/[A-Fa-f0-9]/ #matches any hexadecimal digit

Lookahead assertionsTo match numbers only if it ends with a period,

str = "123 456. 789" m = /\d+(?=\.)/.match(str)

Strings and regex interchangeabilityString to regex

str = “def”/abc#{str}/

str = “a.c”re = /#{Regexp.escape(str)}/ # = /a\.c/

From regex to stringputs /abc/ #output: (?-mix:abc)p /abc/ #output: /abc/

Ruby Cheatbook by rubynerds.blogspot.com

Page 12: Ruby Cheatbook

MATCHDATA AND GLOBAL VARIABLES

When a regex matching is performed with parenthetical groupings:

/([A-Za-z]+), [A-Za-z]+(Mrs?\.)/ .match(str)

the results of the match (submatches), if any was found, is:1) Ruby populates a series of global variables to

access those matches2) 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 useputs “1st match:#{$1} & 2nd:#{2}”

MatchDatastring = “My number is (123) 555-1234.”pattern =/\((\d{3})\)\s+(\d{3})-(\d{4})/m = pattern.match(string)

Method + Sample call Descriptionm.string Returns the entire string

matchedm.captures(index) Returns the submatch

referenced by index (start from 0)

m[0] Entire matchm[1],m[2],etc Same as captures (start from 1)

m.pre_match Returns part of string before match

m.post_match Returns part of string after match

m.begin(index) Returns the position of 1st

character matched in submatch referenced by index

m.end(index) Returns the position of last character matched in submatche referenced by index

METHODS THAT USE REGEX

String#scanscan goes from left to right thru a string, looking for a match for the pattern specified. Results are returned in an array.

“testing 1 2 3 testing 4 5 6”.scan(/\d/)

returns the array:[“1”, “2”, “3”, “4”, “5”, “6”]

if regex is parenthetically grouped, then scan returns an array of arrays.

String#splitSplit 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.

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

Or using code blocks,“capitalize the first vowel”.

sub([aeiou]/){|s| s.upcase}

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')

grepgrep does a select operation on an array based on a regex argument.

[“USA”, “UK”, “France”, “Germany”]. grep(/[a-z]/)

grep can also take code blocks["USA", "UK", "France", "Germany"].

grep(/[a-z]/) {|c| c.upcase }

Ruby Cheatbook by rubynerds.blogspot.com

Page 13: Ruby Cheatbook

Ruby Dynamics

SINGLETON CLASSES

To get inside the definition body of a singleton class,class << object

#method and constant definitionsend

Class methods can be defined this way within the body of the class definition:

class Ticketclass << self

#method and constant definitionendetc...

end

THE EVAL FAMILY OF METHODS

evaleval 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 eval("def #{m}; puts 'Hi!'; end") eval(m)

whenever the code is run and user types in a name, a method by that name is then created. Note: the code above lets users in on program definition. Given the right commands, eval lets users hack into your program, and even system.

instance_evalEvaluates string or code block given to it, changing self to be the receiver of instance_eval

p self #output: maina = []a.instance_eval(p self) #output: []

This method is useful for obtaining acces to another object's private data.

class Cdef initialize

@x = 1end

end

c = C.newc.instance_eval {puts @x}

class_eval (a.k.a module_eval)This method puts you inside a class definition body

var = “var”class C

puts var #returns NameErrorend

C.class_eval {puts var} #returns “var”

To define an instance method using an outer-scope variable with class_eval, use the define_method method.

C.class_eval { define_method("talk") { puts var }}

CALLABLE OBJECTS

Proc objectsProc 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– it is originally created

def call_some_proc(pr) a = "irrelevant 'a' in method scope" puts a pr.call end a = "'a' to be used in Proc block" pr = Proc.new { puts a } pr.call call_some_proc(pr)

The output for the above is as follows:'a' to be used in Proc block irrelevant 'a' in method scope 'a' to be used in Proc block

Proc objects can take argumentspr = Proc.new {|x| p x}pr.call(100)

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)

#output: 1# 2# nil

pr.call(1,2,3,4)#output: 1# 2# 3

lambdalambda creates an anonymous function

lam = lambda{puts “A lambda!”}lam.call #output: “A lambda!”

lambda is a subclass of Proc. The difference from Proc is lambda returns from lambda, Proc returns from the method it's encapsulated in.

Ruby Cheatbook by rubynerds.blogspot.com

Page 14: Ruby Cheatbook

Convert code blocks into Proc objectsDone 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 objectsmethods 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 unbind self and bind to another object, use unbind and bind method. This can only be done if the other object is the same class or subclass of the original object.

class D < C end d = D.new unbound = meth.unbind unbound.bind(d).call

CALLBACKS AND HOOKS

method_missingclass C def method_missing(m)

puts "No method called #{m} -- please try again."

end end C.new.anything

Module#includedIf 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 Cinclude M

end

Class#inheritedIf 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

by #{subclass}" end end

class D < C end

Note: inherited functions are inherited by its subclasses. Subclasses of the subclasse will also trigger inherited.

Module#const_missingThis 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

OVERRIDING AND ADDING TO CORE FUNCTIONALITY

Ruby's core functionality can always be redefined easilyclass Array def shuffle sort_by { rand } end end

Note: be careful, as you may cause problems if your program is shared with other developers.

Ruby Cheatbook by rubynerds.blogspot.com