SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
Ruby Cheat Sheet
This cheat sheet describes Ruby features in roughly the order they'll be presented in
class. It's not a reference to the language. You do have a reference to the language – it's
in ProgrammingRuby-the-book-0.4 on your CD. Click on index.html in that folder, and
you'll find most of the text of Andy Hunt and Dave Thomas's fine book Programming
Ruby.

Variables
Ordinary ("local") variables are created through assignment:
number = 5
Now the variable number has the value 5. Ordinary variables begin with lowercase
letters. After the first character, they can contain any alphabetical or numeric character.
Underscores are helpful for making them readable:
this_is_my_variable = 5
A variable's value is gotten simply by using the name of the variable. The following has
the value 10:
number + this_is_my_variable

Conditional tests (if)
if number == 5
puts "Success"
else
puts "FAILURE"
end

A string. Strings can be
surrounded with single or
double quotes.

Put the if, else, and end on separate lines as shown. You don't have to indent, but you
should.

Function calls
puts "hello"
puts("hello")

parentheses can be omitted if not required.
If you're not sure whether they're required,
put them in. To be safe, put them in whenever
the call is at all complicated. Even one as
simple as this.

assert_equal(5, number)

Copyright © 2003 by Brian Marick and Bret Pettichord. All rights reserved.
Function definitions
def assert_equal(expected, actual)
if expected != actual
puts "FAILURE!"
end
end
Functions can return values, and those values can be assigned to variables. The return
value is the last statement in the definition. Here's a simple example:
def five
5
end

Note that no parentheses are required.

variable = five

Variable's value is 5. Note that we didn't
need to say five(), as is required in
some languages. You can put in the
parentheses if you prefer.

Here's a little more complicated example:
def make_positive(number)
if number < 0
-number
else
number
end
end
variable = make_positive(-5)
variable = make_positive(five)

Variable's value is 5.
Variable's value is 5.

Very simple regular expressions
Regular expressions are characters surrounded by // or %r{}. A regular expression is
compared to a string like this:
regexp =~ string
Most characters in a regular expression match the same character in a string. So, these all
match:
/a/ =~ 'a string'
/a/ =~ 'string me along'
This also matches:
/as/ =~ 'a string with astounding length'

Ruby Cheat Sheet

2
Notice that the regular expression can match anywhere in the string. If you want it to
match only the beginning of the string, start it with a caret:
/^as/ =~ 'alas, no match'
If you want it to match at the end, end with a dollar sign:
/no$/ =~ 'no match, alas'
If you want the regular expression to match any character in a string, use a period:
/^.s/ =~ "As if I didn't know better!"
There are a number of other special characters that let you amazing and wonderful things
with strings. See Programming Ruby.

Truth and falsehood (optional)
Read this only if you noticed that typing regular expression matching at the interpreter
prints odd results.
You'll see that the ones that match print a number. That's the position of the first
character in the match. The first expression (/a/ =~ 'a string') returns 0. (Ruby,
like most programming languages, starts counting with 0.) The second returns 10.
What happens if there's no match? Type this:
/^as/ =~ 'alas, no match'
and the result will be nil, signifying no match. You can use these results in an if, like
this:
if /^as/ =~ some_string
puts 'the string begins with "as".'
end
In Ruby, anything but the two special values false and nil are considered true for
purposes of an if statement. So match results like 0 and 10 count as true.

Objects and methods and messages
A function call looks like this:
start('job')
A method call looks much the same:
"bookkeeper".include?('book') returns true
The difference is the thing before the period, which is the object to which the message is
sent. That message invokes a method (which is like a def'd function). The method
operates on the object.
Different types of objects respond to different messages. Read on to see two important
types of objects.
Ruby Cheat Sheet

3
Arrays
This is an array with nothing in it:
[]
This is an array with two numbers in it:
[1, 2]
This is an array with two numbers and a string in it. You can put anything into an array.
[1, 'hello!', 220]
Here's how you get something out of an array:
array = [1, 'hello', 220]
array[0]
value is 1
Here's how you get the last element out:
array[2]

value is 220

Here's another way to get the last element:
array.last

value is 220

Here's how you change an element:
array[0]= 'boo!'

value printed is 'boo!'
array is now ['boo', 'hello', 220]

How long is an array?
array.length

value is 3

Here's how you tack something onto the end of an array:
array.push('fred')

array is now ['boo', 'hello', 220, 'fred']

There are many other wonderful things you can do with an array, like this:
[1, 5, 3, 0].sort

value is [0, 1, 3, 5]

a = ["hi", "bret", "p"]
a.sort
value is ["bret", "hi", "p"]

Hashes (or dictionaries)
A hash lets you say "Give me the value corresponding to key." You could use a hash to
implement a dictionary: "Give me the definition (value) for the word (key) 'phlogiston'?"
So hashes are sometimes called dictionaries. ("Dictionary" is actually a better name, but
"hash" is the official one.)
Here's how you create a hash:
hash = {}
Here's how you associate a value with a key:
Ruby Cheat Sheet

4
hash['bret'] = 'texas'

looks a lot like an array, except that the key
doesn't have to be a number.

Here's how you retrieve a value, given a key:
hash['bret']

value is 'texas'.

Here's how you know if a hash has a key:
hash.has_key?('bret')

value is true.

Here's how you ask how many key/value pairs are in the hash:
hash.length

value is 1

Here's how you ask if a hash is empty:
hash.empty?

value is false.

What values does a hash have?
hash.values

value is the Array ['texas'].

What keys does it have?
hash.keys

value is the Array ['bret'].

Iteration
How can you do something to each element of an array? The following prints each value
of the array on a separate line.
[1, 2, 3].each do | value |
puts value
end
If you prefer, you can use braces instead of do and end:
[1, 2, 3].each { | value |
puts value
}
What if you want to transform each element of an array? The following capitalizes each
element of an array.
["hi", "there"].collect { | value |
value.capitalize
}
The result is ["Hi", "There"].
This barely scratches the surface of what you can do with iteration in Ruby.

Ruby Cheat Sheet

5

Contenu connexe

Tendances

Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe Jiang
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 

Tendances (20)

Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2
 
Php
PhpPhp
Php
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
Perl_Part4
Perl_Part4Perl_Part4
Perl_Part4
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Php1
Php1Php1
Php1
 
lab4_php
lab4_phplab4_php
lab4_php
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Bioinformatics p2-p3-perl-regexes v2014
Bioinformatics p2-p3-perl-regexes v2014Bioinformatics p2-p3-perl-regexes v2014
Bioinformatics p2-p3-perl-regexes v2014
 
Data types in php
Data types in phpData types in php
Data types in php
 
PHP
 PHP PHP
PHP
 

Similaire à Ruby cheat sheet

Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raghu nath
 
Hw1 rubycalisthenics
Hw1 rubycalisthenicsHw1 rubycalisthenics
Hw1 rubycalisthenics
shelton88
 
PERL Regular Expression
PERL Regular ExpressionPERL Regular Expression
PERL Regular Expression
Binsent Ribera
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
Harkamal Singh
 

Similaire à Ruby cheat sheet (20)

Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)
 
perl 6 hands-on tutorial
perl 6 hands-on tutorialperl 6 hands-on tutorial
perl 6 hands-on tutorial
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docx
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
 
Regex lecture
Regex lectureRegex lecture
Regex lecture
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014
 
Hw1 rubycalisthenics
Hw1 rubycalisthenicsHw1 rubycalisthenics
Hw1 rubycalisthenics
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
Perl_Part6
Perl_Part6Perl_Part6
Perl_Part6
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
PERL Regular Expression
PERL Regular ExpressionPERL Regular Expression
PERL Regular Expression
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
The Bund language
The Bund languageThe Bund language
The Bund language
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Ruby cheat sheet

  • 1. Ruby Cheat Sheet This cheat sheet describes Ruby features in roughly the order they'll be presented in class. It's not a reference to the language. You do have a reference to the language – it's in ProgrammingRuby-the-book-0.4 on your CD. Click on index.html in that folder, and you'll find most of the text of Andy Hunt and Dave Thomas's fine book Programming Ruby. Variables Ordinary ("local") variables are created through assignment: number = 5 Now the variable number has the value 5. Ordinary variables begin with lowercase letters. After the first character, they can contain any alphabetical or numeric character. Underscores are helpful for making them readable: this_is_my_variable = 5 A variable's value is gotten simply by using the name of the variable. The following has the value 10: number + this_is_my_variable Conditional tests (if) if number == 5 puts "Success" else puts "FAILURE" end A string. Strings can be surrounded with single or double quotes. Put the if, else, and end on separate lines as shown. You don't have to indent, but you should. Function calls puts "hello" puts("hello") parentheses can be omitted if not required. If you're not sure whether they're required, put them in. To be safe, put them in whenever the call is at all complicated. Even one as simple as this. assert_equal(5, number) Copyright © 2003 by Brian Marick and Bret Pettichord. All rights reserved.
  • 2. Function definitions def assert_equal(expected, actual) if expected != actual puts "FAILURE!" end end Functions can return values, and those values can be assigned to variables. The return value is the last statement in the definition. Here's a simple example: def five 5 end Note that no parentheses are required. variable = five Variable's value is 5. Note that we didn't need to say five(), as is required in some languages. You can put in the parentheses if you prefer. Here's a little more complicated example: def make_positive(number) if number < 0 -number else number end end variable = make_positive(-5) variable = make_positive(five) Variable's value is 5. Variable's value is 5. Very simple regular expressions Regular expressions are characters surrounded by // or %r{}. A regular expression is compared to a string like this: regexp =~ string Most characters in a regular expression match the same character in a string. So, these all match: /a/ =~ 'a string' /a/ =~ 'string me along' This also matches: /as/ =~ 'a string with astounding length' Ruby Cheat Sheet 2
  • 3. Notice that the regular expression can match anywhere in the string. If you want it to match only the beginning of the string, start it with a caret: /^as/ =~ 'alas, no match' If you want it to match at the end, end with a dollar sign: /no$/ =~ 'no match, alas' If you want the regular expression to match any character in a string, use a period: /^.s/ =~ "As if I didn't know better!" There are a number of other special characters that let you amazing and wonderful things with strings. See Programming Ruby. Truth and falsehood (optional) Read this only if you noticed that typing regular expression matching at the interpreter prints odd results. You'll see that the ones that match print a number. That's the position of the first character in the match. The first expression (/a/ =~ 'a string') returns 0. (Ruby, like most programming languages, starts counting with 0.) The second returns 10. What happens if there's no match? Type this: /^as/ =~ 'alas, no match' and the result will be nil, signifying no match. You can use these results in an if, like this: if /^as/ =~ some_string puts 'the string begins with "as".' end In Ruby, anything but the two special values false and nil are considered true for purposes of an if statement. So match results like 0 and 10 count as true. Objects and methods and messages A function call looks like this: start('job') A method call looks much the same: "bookkeeper".include?('book') returns true The difference is the thing before the period, which is the object to which the message is sent. That message invokes a method (which is like a def'd function). The method operates on the object. Different types of objects respond to different messages. Read on to see two important types of objects. Ruby Cheat Sheet 3
  • 4. Arrays This is an array with nothing in it: [] This is an array with two numbers in it: [1, 2] This is an array with two numbers and a string in it. You can put anything into an array. [1, 'hello!', 220] Here's how you get something out of an array: array = [1, 'hello', 220] array[0] value is 1 Here's how you get the last element out: array[2] value is 220 Here's another way to get the last element: array.last value is 220 Here's how you change an element: array[0]= 'boo!' value printed is 'boo!' array is now ['boo', 'hello', 220] How long is an array? array.length value is 3 Here's how you tack something onto the end of an array: array.push('fred') array is now ['boo', 'hello', 220, 'fred'] There are many other wonderful things you can do with an array, like this: [1, 5, 3, 0].sort value is [0, 1, 3, 5] a = ["hi", "bret", "p"] a.sort value is ["bret", "hi", "p"] Hashes (or dictionaries) A hash lets you say "Give me the value corresponding to key." You could use a hash to implement a dictionary: "Give me the definition (value) for the word (key) 'phlogiston'?" So hashes are sometimes called dictionaries. ("Dictionary" is actually a better name, but "hash" is the official one.) Here's how you create a hash: hash = {} Here's how you associate a value with a key: Ruby Cheat Sheet 4
  • 5. hash['bret'] = 'texas' looks a lot like an array, except that the key doesn't have to be a number. Here's how you retrieve a value, given a key: hash['bret'] value is 'texas'. Here's how you know if a hash has a key: hash.has_key?('bret') value is true. Here's how you ask how many key/value pairs are in the hash: hash.length value is 1 Here's how you ask if a hash is empty: hash.empty? value is false. What values does a hash have? hash.values value is the Array ['texas']. What keys does it have? hash.keys value is the Array ['bret']. Iteration How can you do something to each element of an array? The following prints each value of the array on a separate line. [1, 2, 3].each do | value | puts value end If you prefer, you can use braces instead of do and end: [1, 2, 3].each { | value | puts value } What if you want to transform each element of an array? The following capitalizes each element of an array. ["hi", "there"].collect { | value | value.capitalize } The result is ["Hi", "There"]. This barely scratches the surface of what you can do with iteration in Ruby. Ruby Cheat Sheet 5