SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Perl programming language
Perl programming languagePerl programming language
Perl programming languageElie Obeid
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2Rakesh Mukundan
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perlsana mateen
 
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 perlsana mateen
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
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)Roy Zimmer
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Prof. Wim Van Criekinge
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionskeeyre
 
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 

Was ist angesagt? (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
 

Ähnlich wie Ruby cheat sheet

Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
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)FrescatiStory
 
perl 6 hands-on tutorial
perl 6 hands-on tutorialperl 6 hands-on tutorial
perl 6 hands-on tutorialmustafa sarac
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashessana mateen
 
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 .docxajoy21
 
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 expressionssana mateen
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20Max Kleiner
 
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 2014Sandy Smith
 
Hw1 rubycalisthenics
Hw1 rubycalisthenicsHw1 rubycalisthenics
Hw1 rubycalisthenicsshelton88
 
PERL Regular Expression
PERL Regular ExpressionPERL Regular Expression
PERL Regular ExpressionBinsent Ribera
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 TrainingChris Chubb
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptxDurgaNayak4
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 

Ähnlich wie 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
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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 RobisonAnna Loughnan Colquhoun
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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...apidays
 

Kürzlich hochgeladen (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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...
 

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