ruby built-ins cheatsheet

9
The Basics LITERAL CONSTRUCTORS STRING “new string” Or 'new string' SYMBOL :symbol Or :”symbol with spaces” ARRAY Square brackets [1,2,3,4,5] HASH Curly braces {} {“New York” => “NY”, “Oregon” => “OR”} RANGE Two or three dots 0..10 Or 0...10 REGULAR EXPRESSION (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 How ruby sees it Sugared syntax x = x + 1 x += 1 x = x – 1 x –= 1 x = x * 2 x *= 2 x = x / 2 x /= 2 x = x % 2 x %= 2 GET/SET/APPEND DATA Definition Calling example Sugared syntax def [](x) obj.[](x) obj [ x] def []= (x,y) obj.[]=(x,y) obj [ x]= y def << (x) obj.<<(x) obj << x COMPARISON METHOD 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 CASE EQUALITY (FOR CASE/WHEN) Definition Calling example Sugared syntax def === (x) obj.===(x) 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 Built – Ins BUILT-IN CONVERSION METHODS to_s #to string to_i #to integer to_a #to array to_f #to float Ruby Built-ins Cheatsheet (based on Ruby for Rails by David Black) Compiled by Acap @ rubynerds.blogspot.com

Upload: asyraf

Post on 13-Nov-2014

4.151 views

Category:

Documents


3 download

DESCRIPTION

Part 2 of the Ruby Cheatsheet. Built-ins - for more advanced Ruby programmers. Based on "Ruby for Rails" by David Black

TRANSCRIPT

Page 1: Ruby Built-ins Cheatsheet

The Basics

LITERAL CONSTRUCTORS STRING

“new string”

Or'new string'

SYMBOL:symbol

Or:”symbol with spaces”

ARRAY

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

HASH

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

RANGE

Two or three dots0..10

Or0...10

REGULAR EXPRESSION (REGEXP)/([a-z]+)/

SYNTACTIC SUGAR ARITHMETIC

Definition 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

How ruby sees it Sugared syntaxx = x + 1 x += 1

x = x – 1 x –= 1

x = x * 2 x *= 2

x = x / 2 x /= 2

x = x % 2 x %= 2

GET/SET/APPEND DATA

Definition 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 METHOD

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

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

Built – Ins

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

Ruby Built­ins Cheatsheet

(based on Ruby for Rails by David Black)

Compiled by Acap @ rubynerds.blogspot.com

Page 2: Ruby Built-ins Cheatsheet

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

-1elsif 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

Page 3: Ruby Built-ins Cheatsheet

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

ascii_value = 97.chrstr = 2.ro_s

COMMON ARITHMETIC EXPRESSIONS

Expression Result Description1 + 1 2 Addition

10/3 3 Integer Division

10.0/3.0 3.333333 Floating-point Division

-12 - - 7 -5 Subtraction negative number

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

Page 4: Ruby Built-ins Cheatsheet

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]

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[1,2,3,4,5].each {|x| puts x*10}[1,2,3,4,5].each_with_index do |x,i|

puts “element #{i} is #{x}”end

The map method returns a new arraya = [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}

This filter removes all occurences of criteria in code block[1,2,3,4,5,6,7].reject{|x| x > 5}

ARRAY QUERYING

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

array

h.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”}

Page 5: Ruby Built-ins Cheatsheet

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

For iterating through all the keys/valuesh.keys #{10, 20}h.values #{“ten, “twenty”}

Orh.each_key{|k| #code here }h.each_value{|v| #code here }

For filtering through hashesh.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 arraynew_hash = h.map {|k,v| k > 10}

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 methods

selectrejectfindmap

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

Page 6: Ruby Built-ins Cheatsheet

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

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 character

Regex 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 modifiers

Notation 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

Page 7: Ruby Built-ins Cheatsheet

/[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/

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 use

puts “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

matchm.post_match Returns part of string after

matchm.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#scan

scan 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:

Page 8: Ruby Built-ins Cheatsheet

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

Page 9: Ruby Built-ins Cheatsheet

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

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