Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Look up keyword
Like this
24Activity
0 of .
Results for:
No results containing your search query
P. 1
Ruby Built-ins Cheatsheet

Ruby Built-ins Cheatsheet

Ratings:

4.73

(15)
|Views: 4,142 |Likes:
Published by Asyraf
Part 2 of the Ruby Cheatsheet. Built-ins - for more advanced Ruby programmers. Based on "Ruby for Rails" by David Black
Part 2 of the Ruby Cheatsheet. Built-ins - for more advanced Ruby programmers. Based on "Ruby for Rails" by David Black

More info:

Published by: Asyraf on May 12, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

05/09/2014

pdf

text

original

 
The Basics
L
ITERAL
C
ONSTRUCTORS
 S
TRING
“new string”
Or
'new string'
S
YMBOL
:symbol
Or
:”symbol with spaces”
A
RRAY
Square brackets
[1,2,3,4,5]
H
ASH
Curly braces {}
{“New York” => “NY”, “Oregon” => “OR”}
R
ANGE
Two or three dots
0..10
Or
0...10
R
EGULAR
 
EXPRESSION
(
REGEXP
)
/([a-z]+)/
S
YNTACTIC
S
UGAR
 A
RITHMETIC
DefinitionCalling exampleSugared syntax
def + (x)obj.+(x)obj + xdef (x)obj.(x)obj xdef * (x)obj.*(x)obj * xdef / (x)obj./(x)obj / xdef % (x)obj.%(x)obj % x
How ruby sees itSugared syntax
x = x + 1x += 1x = x 1x = 1x = x * 2x *= 2x = x / 2x /= 2x = x % 2x %= 2
G
ET
/S
ET
/A
PPEND
 
DATA
DefinitionCalling exampleSugared syntax
def [](x)obj.[](x)obj [ x]def []= (x,y)obj.[]=(x,y)obj [ x]= ydef << (x)obj.<<(x)obj << x
C
OMPARISON
 
METHOD
DefinitionCalling exampleSugared syntax
def ==(x)obj.==(x)obj == xdef > (x)obj.>(x)obj > xdef < (x)obj.<(x)obj < xdef >= (x)obj.>=(x)obj >= xdef <= (x)obj.<=(x)obj <= x
C
ASE
 
EQUALITY
(
FOR
 
CASE
/
WHEN
)
DefinitionCalling exampleSugared syntax
def === (x)obj.===(x)obj === x
B
ANG
 
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-bangequivalents,
modify their receivers.
Examples:
str = “hello”puts str.upcase #output: HELLOputs str #output: helloputs str.upcase!#output: HELLOputs str #output: HELLO
Built – Ins
B
UILT
-
IN
 
CONVERSION
 
METHODS
to_s #to stringto_i #to integerto_a #to arrayto_f #to float
Ruby Built-insCheatsheet
(based on Ruby for Rails by DavidBlack)Compiled by Acap @ rubynerds.blogspot.com
 
These methods are defined by default for most objects.However, you can also define them for your objects usingthe standard def statement.
B
UILT
-
IN
 
EQUALITY
 
TESTS
Apart from the usual comparison operators, the followingmethods are also built-in for most objects.
obj.eql?obj.equal?
C
OMPARABLE
class Bidinclude Comparableattr_accessor :contractorattr_accessor :quote#This is called the spaceship#operator – must always return -1, 1,#or 0def <=>(other_bid)if self.quote < other_bid.quote-1elsif self.quote > other_bid.quote1else0endendend
Once this function is defined, use it by using the usualless_than, larger_than or equal_to operators
a < ba > ba == b
Strings and Symbols
S
TRING
 
QUOTING
 
MECHANISM
TokenExample
' ''You\'ll have to “escape” singlequotes'“ ““You'll have to \”escape\” doublequotes”%q%q{'Single quoted' example – noescape}%Q%Q{“Double quoted” example – noescape}
C
OMBINING
 
STRINGS
“a” + “b” + “c”str = “Hi ”puts str + “There” #output: Hi Thereputs str #output: Hiputs “#{str}There” #output: Hi Thereputs str #output: Hiputs str << ”There”#output: Hi Thereputs str #output: Hi There
R
EPLACING
 
A
 
STRING
'
S
 
CONTENTS
str = “Hi There”puts str#output: Hi Therestr.replace(“Goodbye”)puts str #output: Goodbye
M
ASSAGING
 
STRINGS
str = “ruby”str.capitalize#output: Rubystr.reverse#output: yburstr.upcase#output: RUBYstr = “RUBY”str.downcase#output: “rubystr = “Ruby”str.swapcase#output: “rUBYstr.chop#output: Rubstr = “ Ruby “str.strip#output: Rubystr.lstrip#output: Ruby str.rstrip#output: Rubystr = “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: cputs str[1,2] #output: bc
Setter methods ( [ ]=)
str = “abc”puts str[2] = “d” #output: abd puts str[1,2] = “ge” #output: age
S
TRING
 
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 ASCIIvalues of the characters in a string
“a” < “b” #output: true“a” < “A” #output: true
 
S
YMBOLS
only one symbol object can exist for any given unit of text
:a:venue“a”.to_sym“a”.intern
U
NIQUENESS
 
OF
 
SYMBOLS
:a.equal?(:a) #output: true
R
AILS
 
STYLE
 
METHOD
 
ARGUMENTS
<%= link_to "Click here",:controller => "book",:action => "show",:id => book.id %>
Numerical Objects
S
ENDING
M
ESSAGES
 
TO
N
UMBERS
x=12x.zero?n = 98.6m = n.roundascii_value = 97.chrstr = 2.ro_s
C
OMMON
 
ARITHMETIC
 
EXPRESSIONS
ExpressionResultDescription
1 + 12Addition10/33Integer Division10.0/3.03.333333Floating-point Division-12 - - 7-5Subtraction negativenumber
N
ON
-
DECIMAL
 
NUMBERS
Hexadecimal integers
0x12 #equals 18
Octal integers (begin with 0)
012 #equals 10
to_i conversion from any base to decimal. Supply the baseto 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:
DateTimeDateTime
'require' the classes into your program to use them
M
ETHODS
d = Date.today #returns today's dateputs d << 2 #rewind date by 2 monthsputs d >> 5 #advance date by 5 monthst = Time.newt.yeart.montht.dayt.hourt.mint.sect.usect.strftime(“%m-%d-%Y”)
SpecifierDescription%YYear (4 digits)%yYear (las 2 digits)%b, %BShort month, full month%mMonth (number)%dDay of month (left padded with zeros)%eDay of months(left padded with blanks)%a, %AShort day name, full day name%H, %IHour (24h), hour (12h am/pm)%MMinute%SSecond%cEquals %a %b %d %H:%M:%S %Y
%x Equals %m/%d/%y
Arrays and Hashes
C
REATING
 
ARRAYS
a = Array.newa = []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

Activity (24)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
Luke Hamilton liked this
unita_logica liked this
kruthi liked this
Ken Egozi liked this
Daniel Price liked this
Mukesh Bhati liked this

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->