- Comments start with a pound character, and go to the end of the line
- For multi-line comments use "=begin" and "=end"
- Expressions are finished with a semi-colon, followed by a new line
- Including a backslash () at the end of a line does not terminate the expression
- 123 1_234 123.45 1.2e-3
- 0xffff (hex) 0b01011 (binary) 0377 (octal)
- ?a = ASCII character
- ?\C-a = Control-A
- ?\M-a = Meta-A
- ?\M-\C-a = Meta-Control-A
- no interpolation
- # (interpolation) and backslashes \n
- %q (no interpolation
- %Q (interpolation and backslashes)
- % (interpolation and backslashes)
- echo command intrepretation with interpolation and backslashes
- %x (echo command intrepretation with interpolation and backslashes)
1..10
1...10
"a".."z"
"a"..."z"
(1..10) === 5 # true
(1..10) === 10 # false
(1...10) === 10 # false
(1..10) === 15 # false
alias, and, BEGIN, begin, break, case, class, def, defined?, do, else, elsif, END, end, ensure, false, for, if, module, next, nil, not, or, redo, rescue, retry, return, self, super, then, true, undef, unless, until, when, while, yield, __FILE__, __LINE__
# Snake case for file names
customer_import.rb
# Snake case for methods, variables and symbols
first_name = 'Mike'
def display_customer
# ...
# ...
end
:light_red
# All uppercase for constants
API_KEY = 'ZZQ112'
# Capital-case for classes and modules
class SupervisingManager
# ...
# ...
end
module TechnicalSupport
# ...
# ...
end
- $global_variable
- @@class_variable
- @instance_variable
- CONSTANT
- ::TOP_LEVEL_CONSTANT
- SomeClass::CONSTANT
- local_variable
TRUE
- true valueFALSE
- false valueNIL
- nil valueSTDIN
- standard input and default value for $stdinSTDOUT
- standard output and default value for $stdoutSTDERR
- standard error output and default value for $stderrENV
- hash which contains current environment variablesARGF
- alias to $<. ARGV, meta-IO across all filesARGV
- array of all arguments given on runDATA
- file object of the scriptRUBY_VERSION
- version stringRUBY_ENGINE
- ruby implementation runningRUBY_RELEASE_DATE
- release date string for versionRUBY_PLATFORM
- platform identifier
# Strings
full_name = 'Joe Smith'
# Integers
count = 20
# Floating-point Numbers
book_price = 12.10
# Boolean Values
active? = true
root_user? = false
# Array Types
fruits = [ 'Pineapple', 'Banana', 'Kiwi' ]
# Hash
fruit_color = { banana: 'yellow' }
# Array of hashed-types
customers = [
{ id: 2000, name: 'Joe Smith' },
{ id: 3001, name: 'John Q' },
{ id: 4002, name: 'Sir Harrington' }
]
# Struct Types
Person = Struct.new(:name, :age)
person1 = Person.new 'joe', 22
person2 = Person.new 'mike', 12
# Set to 'Default Value' only if nil or false
title = custom_title || 'Default Value'
# Perform assignment if null
search ||= params[:search]
# Safe navigation operator &. (skip if nil)
name = customer&.first_name
self
- receiver of the current methodnil
- instance of class NilClasstrue
- instance of class TrueClassfalse
- instance of class FalseClass__FILE__
- current source file name__LINE__
- current line number in source file
DEBUG
- boolean status of the -d switchFILENAME
- current input file from ARGFLOAD_PATH
- load path for scripts and binary modulesstderr
- current standard error outputstdin
- current standard inputstdout
- current standard outputVERBOSE
- verbose flag, as set by the -v switch$!
- exception object passed to #raise$@
- stack backtrace generated by last exception raised$&
- string matched by last successful match$;
- string to the left of last successful match$`
- string to the right of last successful match$+
- highest group matched by last successful match$1
- The nth group of last successful match$~
- MatchData instance of last match$=
- flag for case insensitive (defaults to NIL)$/
- input record separator$\
- output record separator$,
- output field separator for print and array$;
- default separator for string$.
- current line number for last file from input$>
- default output for print, and printf$0
- name of script being executed$$
- process number of ruby running the script$?
- status of last executed child process
# Print with line break
puts 'This string will print on screen with a line break'
# Print with no line break
print 'The string will print on the screen with no line break'
+, *
- Adds two strings together, repeat the stringlength
- How long the string isstrip
- Removes leading and trailing white spaceto_i
- Changes a string into a numberupcase, downcase
- Changes the case of the stringeach_char
- Loops through the string returning each characterinclude?
- Returns true if a string is in another string[]
- Returns character or substringgsub
- Substitutes a new string where a pattern is found
# Get the length of a string
'This is a string'.length # 16
# Check to see if the string has no length
'Hello World'.empty? # false
''.empty? # true
# Convert all characters to uppercase
'you can do it'.upcase # YOU CAN DO IT
# Convert all characters to lowercase
'HELLO WORLD'.downcase # hello world
# Convert first character to uppercase return the rest lowercase
'jOHN'.capitalize # John
# Remove white space from beginning/end of a string
' This is a string with space '.strip
# Return a string left justified and padded with a character
'strin'.ljust(20, '.') # 'strin...............'
# Check if a string include specified character(s), case sensitive
'hello World'.include? 'hello' # true
# Chaining 2 or more methods together
'Hello World'.downcase.include? 'world' # true
# Finding an index position (start at postion 0)
'Welcome to this web site'.index('web') # 16
# Return string character(s) (indices start at position 0)
'This is a string'[3] # s
'This is a string'[0..5] # This i
'This is a string'[-2] # n (last character)
# Replace first sub string
'Hello son my dog'.sub 'son', 'cat'. # Hello cat my dog
# Replace all sub string
'Hello dog my dog'.gsub 'dog', 'spiders'. # Hello spiders my spiders
# Split a string into an array
'Dog Cat Bird'.split ' ' # ["Dog", "Cat", "Bird"]
# Read in input from the console
input = gets
# Read in input, and eat last character (ie. new line)
input = gets.chomp
# Get command-line arguments (ex. ruby main.rb arg1 arg2)
puts ARGV # ['arg1', 'arg2']
ARGV.each { |option| puts option }
+, -, *, /
- Basic arithmetic**2
- Exponentiation (for example, raise to the second power)( )
- Use parentheses to adjust your math operation precedenceeven?
- Returns true if evenodd?
- Returns true if oddround
- Rounds to the nearest integerupto, downto
- Loops up or down from number to another number
2.88.round # 3
2.88.floor # 2
2.68.ceil # 3
3.next # 4
puts 5 / 2 # 2 (integers with integer result integer)
puts 5 / 2.0 # 2.5 (float with integer result float)
puts 3.even? # false
puts 3.odd? # true
# Random number
random_num = rand(1..100000)
# Basic Loop
loop do
puts "Stop loop by using 'break' statement"
break
puts "Skip one occurence by using 'next' statement"
next
end
# While Loop
while number < 200
puts number
number += 1
end
# Looping over a range
(1..100).each { |i| puts i }
(1..100).each do |i|
puts i
end
# Looping a specific number of times
10.times { puts "Hello Ruby!" }
animals = ['Bird', 'Dog', 'Cat']
animals = %w(Bird Dog Cat)
animals.length # 3
animals.first # Bird
animals.last # Cat
animals[0] # Bird
animals[-2] # Dog
animals[3] # nil
animals[1..2] # ['Dog', 'Cat']
# Iteration
animals.each do { |animal| puts animal }
animals.each_with_index do |animal, index|
puts animal # Bird (first loop)
puts index # 0
end
my_array[1]
- Accesses the array in my_array at index 1length
- Returns the length of the array<<, push
- Adds an object at the end of the arraypop
- Removes an object at the end of the arrayinsert
- Adds an object at the start of the arrayshift
- Removes an object at the start of the arraysort
- Sorts the arrayshuffle
- Randomizes positions of objects in the arraysample
- Picks a random object from the arrayeach
- Loops over the array, returning each elementjoin
- Combines each element into a string
animals.include? 'Bird' # true
[1, 5, 2, 4, 3].sort # [1, 2, 3, 4, 5]
[1, 2, 3].reverse # [3, 2, 1]
animals.push 'Lizard' # append at the end
animals << 'Reptile' # append at the end
animals.unshift 'Arachnid' # Append in front
animals.pop # remove last
animals.delete_at(0) # remove first element
animals.shift # remove the first element
animals.join ', ' # 'Bird, Dog, Cat'
# Appending two arrays together
array1 = %w(lizard reptile shark)
array2 = %w(fish hamster)
array3 = array1 + array2 # ["lizard", "reptile", "shark", "fish", "hamster"]
# Concat in the same array
array1.concat array2
puts array1 # ["lizard", "reptile", "shark", "fish", "hamster"]
# Constructing arrays with * splat operator
puts ['dog', *array2, 'bird'] # ['dog', 'fish', 'hamster', bird']
# Equal == And && Or || Not !
if action == 1
puts "action 1"
elsif action < 5
puts "action not 1 but less than 5"
else
puts "action greater than 5"
end
# Unless (negated if statement)
puts 'The user is not deleted' unless deleted == true
# Ternary Operator
deleted ? 'The user is deleted' : 'The user is not deleted'
# Truthy or falsy Values
# false and nil equates to false.
# Every other object like 1, 0, "" all evaluate to true
# Case When Else (similar to switch statement in other languages)
case score
when 0
"F"
when 1..50
"D"
when 51..70
"C""
when 71..99
"B"
when 100
"A"
else
"Score error"
# Convert number to string "456"
456.to_s
# Convert string to integer 456
"456".to_i
# Convert string to float 456.0
"456".to_f
# Creating an array from a range
(1..5).to_a # [1, 2, 3, 4, 5]
('w'..'z').to_a # ['w', 'x', 'y', 'z']
contact_hash[“dad”]
- Accesses the hash in the contact_hash variable using key “dad” and returns its valuecontact_hash[“mom”] = 7878
- Adds new value to the hash stored in the contact_hash variable using key “mom“length
- Returns how many key/value pairs are stored in the hashinclude?
- Checks if a key exists in the hashkeys
- Returns an array of all the keys in the hashvalues
- Returns an array of all the values in the hashempty?
- Returns true if the hash is emptyeach
- Loops over each key/value pair in the hash, returning each pairmerge
- Combines two hashes into one hash, possibly overwriting the first hash’s keys with the second hash’s keys
product = {}
product['title'] = "MSI Laptop"
product[:price] = 2599.99
product = { 'title' => 'MSI Laptop', 'price' => 2599.99 }
# {"title"=>"MSI Laptop", "price"=>2599.99}
product = { title: 'MSI Laptop', price: 2599.99 }
# {:title=>"MSI Laptop", :price=>2599.99}}
# Return default value 0
puts product.fetch(:cost, 0)
product.keys # [:title, :price]
product.values # ['MSI Laptop', 2599.99]
product.each do |key, value|
puts key
puts value
end
Time.now.utc # 2021-01-20 23:15:40 UTC
Time.now.to_i # 1611184555
christmas = Time.new(2021, 12, 25)
puts christmas.wday # return 6 (Friday)
now = Time.now # 2021-01-20 15:16:44 -0800
now.year # 2021
now.month # 1
now.day # 20
now.hour # 15
now.min # 16
now.sec # 33
now.sunday? # false
# Return current time minus 20 seconds
past = Time.now - 60
# 60 secs * 60 mins * 24 hours (1 Day)
past_day = Time.now - 86400
# Only works in Rails
past_day = Time.now - 1.day
# Format Time
# %d Day of the month (01..31)
# %m Month of the year (01..12) Use %-m for (1..12)
# %k Hour (0..23)
# %M Minutes
# %S Seconds (00..60)
# %I Hour (1..12)
# %p AM/PM
# %Y Year
# %A Day of the week (name)
# %B Month (name)
time = Time.new
time.strftime("%d of %B, %Y") # "20 of January, 2021"
'.'
- any character except newline[set]
- any single character of a set[^set]
- any single character not part of a set'*'
- 0 or more previous regular expressions*?
- 0 or more previous regular expressions (non-greedy)+
- 1 or more previous regular expressions+?
- 1 or more previous regular expressions (non-greedy)?
- 0 or 1 previous regular expression|
- alternation()
- grouping of regular expressions^
- beginning of a line or string$
- end of a line or string#{m,n}
- at least M but most N regular expressions#{m,n}?
- at least M but most N regular expressions (non-greedy)\A
- Beginning of a onstring\b
- Backspace (0x08, inside [] only)\B
- Non-word boundary\b
- Word Boundary\d
- Digit, same as [0-9]\D
- Non-digit\S
- Non-whitespace character\s
- Whitespace character [ \t \n \r \f]\W
- Non-word character\w
- Word character [0-9, A-Za-z_]\z
- End of a string\Z
- End of a string or before newline at the end(?#)
- Comment(?:)
- Grouping without back references(?=)
- Zero-width positive look-ahead assertion(?ix-ix)
- Turns on/off i/x options, localized in the group, if any(?ix-ix:)
- Turns on/off i/x options, localized in non-capturing group
# Define a regular expression
zip_code = /\d{5}/
# Attempt to match on "Hello"
"Hello".match zip_code # nil
# Use the zip_code regex to extract the white house zip code
"White House zip: 20500".match zip_code # <MatchData "20500">
# Use the zip_code regex to extract all zip codes
"White House: 20500 and Air Force: 20330".scan zip_code # ['20500', '20330']
# Split a string into an array using a space regex
"Apple Orange Banana".split(/\s+/) # ['Apple','Orange', 'Banana']
[:alnum:]
- Alpha-numeric characters[:alpha:]
- Alphabetic characters[:blank:]
- Whitespace[:cntrl:]
- Control characters[:digit:]
- Decimal digits[:graph:]
- Graph characters[:lower:]
- Lower-case characters[:print:]
- Printable characters[:punct:]
- Punctuation characters[:space:]
- Whitespace including tabs, carriage returns, and more[:upper:]
- Upper-case characterscharacters[:xdigit:]
- Hexadecimal digits
def greeting(name = 'Joe')
"Hello #{name}" # implicit return
end
puts greeting('Paul') # Hello Paul
# Variable number of arguments
def greeting(*names)
names.each { |name| puts "Hello #{name}" }
end
# Named parameters
def display_product(price, options = {})
puts price, options[:hidden], options[:rounded], options[:total]
end
display_product 2599, hidden: false, rounded: false, total: 1222
# Map (return a modified array)
names = [ 'joe', 'pete', 'jake' ]
names_capitalized = names.map do |name|
name.capitalize
end
# ['Joe', 'Pete', 'Jake']
# Short hand version using map
names_capitalized = names.map { |name| name.capitalize }
# Symbol to Ruby proc
names_capitalized = names.map &:capitalize
# Select (return all matches)
products = [
{ name: 'MSI Laptop', active: true, price: 2599.99 },
{ name: 'Samsung Galaxy S', active: false, price: 199.99 },
{ name: 'Kindle Fire', active: true, price: 149.99 },
]
expensive_products = products.select { | product | product[:price] > 1000 }
# Detect (returns first match)
first_inactive_product = products.detect { | product | ! product[:active] }
# Reduce (returns one)
total = products.reduce(0) do |total, product|
total = total + product[:price]
end
puts total.round(2) # 2949.97
# Basic Module
module Display
def hello_world
puts 'Hello World'
end
end
# Mix in
require_relative 'display.rb'
class Customer
include Display
end
Customer.new.hello_world
# Using module as a namespace
module Person
class Customer
def initialize(name)
@name = name
end
end
end
customer = Person::Customer.new('Joe Smith')
# Constants in modules
module Contact
ACCESS_KEY = 'zzz222'
class Person
ACCESS_KEY = 'xyz211'
end
end
puts Contact::ACCESS_KEY
puts Contact::Person::ACCESS_KEY
# Private methods in modules or classes
module Display
# ...
def initialize
greeting
end
private
def greeting
puts 'hello'
end
end
# Basic Class Declaration
class Item
# ...
# ...
end
# Object Instantiation
item = Item.new
# Basi class declaration with constructor and instance variables
class Item
def initialize(name, cost, active)
@name = name
@cost = cost
@active = active
end
end
item = Item.new 'MSI Laptop', 2599, false
# Attribute Accessor (get/set)
class Item
attr_accessor :name, :cost # read/write
attr_reader :name # read only
attr_write :cost # write only
...
end
...
puts item.price # 2599
# instance method
class Item
# ...
def cost_with_tax
# self keyword is optional (10% tax_percent)
self.cost + (self.cost * tax_percent / 100)
end
end
# ...
puts item.price_with_tax # 2858.9
# Static class method and static class variable
def self.calc_tax(amount)
@@count = 1
end
puts Item::calc_tax(1599.99)
# Class Inheritance
class Customer < Person
attr_accessor :number
def initialize(name, number)
super(name)
@number = number
end
end
# Raise an error/exception and output an error message
raise "This is an error"
# Inspect variable value
raise items.inspect # [{:id=>100, :name=>"MSI Laptop"},{:id=>200, :name=>"Samsung Phone"}]
# Exception Handling
begin
# Any exceptions happen here ex. 0 / 1, division by zero
0 / 1
rescue
# when the exception is raised, this code will run
puts "Exception"
handle_exception()
end
# Receive/Handle Exception object
begin
0 / 1
rescue ZeroDivisionError => e
puts e.class.name
puts e.message
end
File.join(p1, p2, ..., pN) => "p1/p2/.../pN"
(platform independent paths)File.new(path, mode_string = "r") => file
File.new(path, mode_num, [, perm_num]) => file
File.open(filename, mode_string = "r") { |file| block } => nil
File.open(filename [,mode_num [, perm_num]]) { |file| block => nil }
IO.foreach(path, sepstring = $/) { |line| block }
IO.readlines(path) => array
"r"
- R/O, start of file (default)"r+"
- R/W, start of file"w"
- W/O, truncates or creates"w+"
- R/W, truncates or creates"a"
- W/O, end of file or creates"a+"
- R/W, end of file or creates"b"
- binary file (DOS/Windows platform)
# Read in a file
text = File.read('test.txt')
# Read a file in by lines
lines = File.readlines("test.txt")
lines.each do |line|
puts "Line: #{line}"
end
# Write to a file
File.write('test.txt', 'write something...')
File.open(“home.html”, “w”) do | file |
file.puts ‘text to write’
end
# Read in a CSV file
require 'csv'
table = CSV.parse(File.read("data.csv"), headers: true)
table[0]["id"] # 1200
table[0]["name"] # "MSI Laptop"
# Write to a CSV file
items = [
{ name: "MSI Laptop", price: 2599 },
{ name: "Android Samsung Phone", price: 999 }
]
CSV.open("data.csv", "w", headers: items.first.keys) do |csv|
items.each { |item| csv << item.values }
end