SlideShare a Scribd company logo
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

More Related Content

PDF
Ruby quick ref
PPTX
Regular Expressions in PHP
PPTX
Learn PHP Basics
ODP
PHP Web Programming
PPT
Class 5 - PHP Strings
PPT
Perl Presentation
PPTX
Php intro by sami kz
PPT
Bioinformatica 06-10-2011-p2 introduction
Ruby quick ref
Regular Expressions in PHP
Learn PHP Basics
PHP Web Programming
Class 5 - PHP Strings
Perl Presentation
Php intro by sami kz
Bioinformatica 06-10-2011-p2 introduction

What's hot (20)

PDF
Perl programming language
PDF
Ruby_Basic
PDF
Practical approach to perl day2
PPTX
PHP Powerpoint -- Teach PHP with this
PPTX
Lesson 2 php data types
PPT
SQL -PHP Tutorial
PDF
Perl_Part4
PPTX
Subroutines in perl
PPTX
Strings,patterns and regular expressions in perl
ODP
Perl Introduction
ODP
perl usage at database applications
PPT
Plunging Into Perl While Avoiding the Deep End (mostly)
PDF
lab4_php
PPTX
Bioinformatics p1-perl-introduction v2013
PDF
Regular expressions
PPTX
Bioinformatics p2-p3-perl-regexes v2014
PPTX
Data types in php
Perl programming language
Ruby_Basic
Practical approach to perl day2
PHP Powerpoint -- Teach PHP with this
Lesson 2 php data types
SQL -PHP Tutorial
Perl_Part4
Subroutines in perl
Strings,patterns and regular expressions in perl
Perl Introduction
perl usage at database applications
Plunging Into Perl While Avoiding the Deep End (mostly)
lab4_php
Bioinformatics p1-perl-introduction v2013
Regular expressions
Bioinformatics p2-p3-perl-regexes v2014
Data types in php
Ad

Similar to Ruby cheat sheet (20)

PPTX
Ruby data types and objects
PPTX
Ruby from zero to hero
ODP
Ruby Basics by Rafiq
PDF
Eloquent ruby
PDF
Ruby training day1
PPTX
Intro to Ruby/Rails at TechLady Hackathon
DOCX
Ruby Programming
PPTX
RUBY PROGRAMMINGRUBY PROGRAMMING RUBY PROGRAMMING
PPTX
Ruby -the wheel Technology
PDF
Learning Ruby
PPTX
Ruby basics
PPTX
Ruby Basics
PDF
RubyMiniGuide-v1.0_0
PDF
RubyMiniGuide-v1.0_0
PDF
06 ruby variables
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
PDF
ruby
PDF
ruby
PDF
a course
PDF
ruby
Ruby data types and objects
Ruby from zero to hero
Ruby Basics by Rafiq
Eloquent ruby
Ruby training day1
Intro to Ruby/Rails at TechLady Hackathon
Ruby Programming
RUBY PROGRAMMINGRUBY PROGRAMMING RUBY PROGRAMMING
Ruby -the wheel Technology
Learning Ruby
Ruby basics
Ruby Basics
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
06 ruby variables
Code for Startup MVP (Ruby on Rails) Session 2
ruby
ruby
a course
ruby
Ad

Recently uploaded (20)

PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
How AI Agents Improve Data Accuracy and Consistency in Due Diligence.pdf
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
creating-agentic-ai-solutions-leveraging-aws.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
DevOps & Developer Experience Summer BBQ
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
How AI Agents Improve Data Accuracy and Consistency in Due Diligence.pdf
Event Presentation Google Cloud Next Extended 2025
madgavkar20181017ppt McKinsey Presentation.pdf
Dell Pro 14 Plus: Be better prepared for what’s coming
Chapter 2 Digital Image Fundamentals.pdf
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Belt and Road Supply Chain Finance Blockchain Solution
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
GamePlan Trading System Review: Professional Trader's Honest Take
creating-agentic-ai-solutions-leveraging-aws.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
Understanding_Digital_Forensics_Presentation.pptx
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
CroxyProxy Instagram Access id login.pptx
Chapter 3 Spatial Domain Image Processing.pdf
DevOps & Developer Experience Summer BBQ
Reimagining Insurance: Connected Data for Confident Decisions.pdf
Enable Enterprise-Ready Security on IBM i Systems.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