Ruby Syntax
Syntax of the Ruby programming language
Printing
# Print a string
puts "Hello World"
print "Hello World"
# Print multiple strings
puts "Hello","World"
# Join/Concatenate two strings (gives errors if not strings)
puts "Hello" + "World"
# Joining two strings with spaces
puts "Hello" + " World"
# Printing numbers
puts 27
# Another way to print (only way in python 3+)
puts("Hello World")
#I've updated the print statements in this script for python 3 users
# Print an empty line (useful for separating code output)
puts('')
Input
# Get number input (works for words and numbers)
puts gets.chomp("How old are you ")
puts gets("How old are you\n")
# Get word/string input
Operators
# Adding
puts(1+2)
# Subtracting
puts(4-3)
# Multiplying
puts(3*3)
# Dividing (not accurate if one of the terms isn't a decimal)
puts(18/3)
# Remainder/Modulus
puts(9%4)
# Power
puts(2**8)
# Suare root
puts(144**(1/2.0)) # must use at least one float
# Comparisons
puts(2<4) #less than
puts(4>9) #greather than
puts(5==6) #is equal to
puts(3==3)
puts(4!=4) #not equal to
puts(4!=9)
Comments
A comment is a note for future or peer reference. The # symbol turns a line into a comment. Comments are not recognized as code, and are often used to disable bits of code. Tripple quotes are a multiline comment. They allow you to write comments that span multiple lines.
Variables
A variable is a container
Data Types
# Character
at = "@"
puts(at)
String (wrapped in quotes)
name = "Raphael"
puts(name)
Integer (no quotes quotes)
age = 29
puts(age)
Float
height = 6.3
puts(height)
Boolean
is_cool = TRUE
puts(is_cool)
Array/List
array = [] #an empty array
array2 = Array.new #another way
array3 = Array[] #and another
array4 = Array(nil) #and another
colors = ["red","orange","yellow","green","blue","indigo","violet"]
numbers = [0,1,2,3,4,5,6,7,8,9]
mixed_array = [9,"alpha",63.3,TRUE]
puts array,colors,numbers,mixed_array
# Another way to create an array
# %W, or %w, with (most) any symbol will make an Array.
print %w^ 1,2,3^
print %w@ 4,5,6@
# Array by index
brr = [:a, :b, :c, :d]
brr[1] = 3
print brr
# Auto fill
crr = [1,2,3]
crr[10] = :foo
print crr
array methods are :pop and :push and the methods for adding and removing from the beginning of an Array are :shift and :unshift.
Tuple
location = Tuple(0,0)
puts(location)
Hash/Dictionary
dictionary = {} #empty dictionary
dictionary1 = Hash.new #another way
dictionary2 = Hash[] #and another
dictionary3 = Hash(nil) #and another
hash = Hash.new
hash[:book_name] = "I am the book"
puts hash[:book_name]
# Example 1
x = {}
x.default = []
puts x.default
x[:a] << 8
x[:b] << 9
x[:c] << 10
print x.default
dictionary = {"key":"value"}
puts(dictionary)
Set
A set is an Array that enforces uniqueness
require 'set'
s = Set.new
s << :a
s << :a
s << :b
s << :c
s << :c
print s.to_a
Struct
a struct allows you to predefine what values you can set by providing keys when created.
Example 1
class Face < Struct.new(:hair, :eyes, :skin)
end
my_face = Face.new :blond, :blue, :awesome
# => #<struct Face hair=:blond, eyes=:blue, skin=:awesome>
my_face[:hair]
# => :blond
my_face.hair
# => :blond
print my_face
Example 2
class PayChecks < Struct.new(:week1, :week2, :week3, :week4)
def total
inject :+
end
end
pay_checks = PayChecks.new 100, 800, 300, 45
# => #<struct PayChecks week1=100, week2=800, week3=300, week4=45>
puts 'Paycheck total: '+pay_checks.total.to_s
# => 1245
OpenStruct
openStruct is similar to Struct but is more “open”; more accepting. You will have to require it with require ‘ostruct’ .
require 'ostruct'
x = OpenStruct.new
puts x[:a]
puts x
puts x[:a] = 0
puts x
puts x.a
puts x.b
puts x
puts x[:b] = 123
puts x
Overwriting a variable
is_cool = FALSE
name = "Tutorial Doctor"
age = 10585 #in days
height = 6.1
puts(is_cool,name,age,height)
Set a boolean to the opposite of itself
is_cool = ! is_cool #False
puts(is_cool)
Casting (changing the type of a variable)
To a float
age = age.to_f
puts(age)
To an integer
height = height.to_i
puts(height)
To a string
is_cool = is_cool.to_s
puts(is_cool)
Other Casting functions
#bool() #To a boolean
#.to_a #To a list
#.to_h #To a dictionary
#.to_c #To a complex
#.to_r #To a rational
#.to_regexp #To a regular expression
Printing the type of a variable
puts is_cool.class
puts height.class,age.class,colors.class,dictionary.class
Python keywords cannot be used as variable names. Variable names can't start with a number Variable names can't start with special characters Use undrescores or camelcasing to separate parts of a variable name
ID of a variable
puts name.object_id
Declaring multiple variables at once
a,s,l = 29,'Male','Georgia'
puts(a)
puts(s)
puts(l)
puts a,s,l
Setting variables to same value at once
a=b=c = 45
puts a,b,c
Strings
# Empty string (two ways)
first_name = ""
last_name = ''
# Assign value to a string
first_name = "Raphael"
last_name = "Smith"
occupation = "Programmer"
Adding strings (concatenation)
puts(first_name + last_name)
Adding a space between string variables
puts(first_name + " " + last_name)
Starting a new line (escape characters)
puts(first_name + "\n" + last_name)
Escaping
message = "I'm not old enough"
# The backslash escapes the apostrophe so it doesn't get inerpreted as a quote
puts(message)
**String Formatting (adding variables inside of a string)**
puts("Hello #{first_name} #{last_name}") #string variables
Number formatting
age = 29
puts("I am #{age} years old")
#digit variable
puts("I am #{"%05d" % age} years old")
#leading zeros
puts("I am #{"%f" % age} years old")
#float
puts("I am #{"%.2f" % age} years old")#truncate decimal places
puts("I am #{"%.6f" % age} years old") #truncate
Another way to format
greeting = "My name is #{first_name} and I am #{age} years old"
puts(greeting)
Another way to use the format() function
greeting = "My name is #{name='Josiah'} and I am #{age=34} years old"
puts(greeting)
Print a string several times
puts(first_name*10)
Get an index of a string (indices start at 0)
puts(first_name[0]) #prints the fist item in the string
puts(first_name[1]) #prints the second item
Indexing backwards
puts(first_name[-1]) #prints the last item in the string
puts(first_name[-2]) #prints the second to last item in the string
Multi-line String
sentence = '''Multi-Line strings are sometimes used as multi-line comments, since python doesn\'t have syntax for multi-line comments. They are usually used for long strings of text, and as docstrings (strings at the beginning of functions that are used for documenting what the function does)'''
puts sentence
More legal syntax
fourth_letter = "Python"[3]
puts(fourth_letter)
String Functions
Capitalize
name = "raphael"
bio = "My name is #{name}, how are you today?"
puts name.capitalize
Uppercase
puts name.upcase
Lowercase
puts name.downcase
Length of string
puts name.length
Split a string into individual words
bio_words = bio.split # returns a list/array of the words
puts(bio_words)
Joining split words into a single string
joined_words = bio_words.join(" ")
puts(joined_words)
Replace items in a string
sentence = 'Jello, how are you today?'
corection = sentence.sub!('J','H')
puts(corection)
Integers
timer = 0
Increment (Add 1 to the time variable)
timer = timer + 2
Another way
timer +=1
puts(timer)
Decrement (Subtract increment)
timer = timer - 1
timer -=1
puts(timer)
Multiply increment
timer *= 10
puts(timer)
Divide Decrement
timer /= 2
puts(timer)
Floats
None
Arrays
# Create an Array
inventory = ["flashlight","map","knife","string"]
clothes = ["shirt","pants","shoes","bandana","hat"]
# Get index of an array (starts at 0)
puts(inventory[0])
# Get last item in array
puts(inventory[-1])
# Array index range (starting at... up to...)
puts(inventory[1..4]) # 2nd to the fourth item
# Array index range (starting at...)
# Array index range (up to...)
#---------------------------------------
# Array Functions
#---------------------------------------
# Append to a array
inventory.push("rope")
puts(inventory)
# Remove from a array
inventory.delete('rope')
puts(inventory)
# Insert item at location
inventory.insert(0,"knife")
puts(inventory)
# Reverse Array
inventory.reverse()
puts(inventory)
# Sort a Array (alphabetical or numerical depending)
inventory.sort()
puts(inventory)
# Remove an item at a location
inventory.pop(1)
puts(inventory)
# Return the index of an item in the array
puts(inventory.index("rope"))
# Extend a array with another array
inventory.concat clothes
puts(inventory)
# Count how many times an item appears in a array
puts(inventory.count("knife"))
puts(inventory.count("rope"))
# Loop through a array
# Remove array from a array
Tuples
(Immutable) can't update indicies
x=0
y=0
position = (x,y)
Hashes
# Create a dictionary: dictionary_name = {key:value}
# Empty dictionary
groceries = {"bread":"Nature's Own"}
# Print the value of a dictionary key
print(groceries["bread"])
# Update Dictionary
groceries.update({"milk":"whole"})
groceries.update({"meat":"ham"})
print(groceries)
# Update key if it is in the dictionary
groceries.update({"milk":"2%"})
print(groceries)
# Get all keys (returns a list)
print(groceries.keys())
# Get all values (returns a list)
print(groceries.values())
# Convert a dictonary to a list of tuples
print(groceries.items())
# Length of a dictionary
print(len(groceries))
# Delete dictionary key
del groceries['meat']
print(groceries)
# Iterate over a dictionary
print(iter(groceries))
print(groceries.iterkeys())
print(groceries.itervalues())
# Remove item, and return it's value
print(groceries.pop("bread"))
# Alternately:
# groceries.popitem()
# Display keys of a dictionary
print(groceries.viewkeys())
# Display values of a dictionary
print(groceries.viewvalues())
# Display items of a dictionary
print(groceries.viewitems())
Classes
class Book
attr_accessor :title, :author, :pages
end
b1 = Book.new
b1.title = "Book 1"
b1.pages = 400
puts b1.title
puts b1.pages
class NewBook
attr_accessor :title, :author, :pages
def initialize(title, author, pages)
@title = title
@author = author
@pages = pages
end
end
b1 = NewBook.new('Game','Me',500)
puts b1.pages
class Chef
def make_chicken
puts "Making some chicken for you"
end
def make_salad
puts "Making some salad for you"
end
def make_special_dish
puts "Making a special dish for you"
end
end
class ItalianChef < Chef
def make_special_dish
puts "Making a special italian dish for you"
end
def make_pasta
puts "Making some pasta for you"
end
end
i_chef = ItalianChef.new()
i_chef.make_chicken
i_chef = ItalianChef.new()
i_chef.make_special_dish
Modules
module Tools
def toolbelt
puts "toolbelt tool"
end
end
include Tools
Tools.toolbelt
module Rails
class Application
def initialize()
puts "Created new application"
end
end
end
include Rails
Rails::Application.new()
module Gem1
def log
puts 'Gem1: ...'
end
end
module Gem2
def log
puts 'Gem2: ...'
end
end
class Logger
include Gem1
include Gem2
end
Logger.ancestors # => [Logger, Gem2, Gem1, Object, Kernel, BasicObject]
#$ global vatiable
$logger = Logger.new
$logger.log # => 'Gem2: ...'
----END OF RUBY----
Control Flow
If, Else if(elif), and Else
age = 9
# 'if' something...
if age>=18:
print('You are too old.')
# otherwise, if something else...
elif age<=7:
print('You are too young.')
# if anything else...
else:
print('You are the right age.')
# The elif statement is optional.
# Try, Except, and Finally: Error Checking
# Try to do something, except if there is an error; do something else. Finally...
try:
print(variable)
except:
print('You have to define the variable first silly.')
variable = 'a_no_longer_undefined_variable'
print('Here, I fixed it for you:\n{}').format(variable)
finally:
print('You have succesfully checked for errors using try and except')
# The variable is now defined, so we can print it
print(variable + '... is defined')
While Loop
As long as...
timer =0
while timer <10:
print(timer)
timer = timer + 1
For Loop
Until...
for number in range(20):
print(number)
for number in range(0,20,2):
print(number)
name = 'Raphael'
for letter in name:
print(letter)
number = 2929392
# The following for loop doesn't work
try:
for digit in number:
print digit
except:
print("You can't loop through numbers")
items = ['gold','wood','ivory','wool']
inventory = {'weapon':'knife','light':'flashlight','navigation':'map'}
# Loop through each value in a list
for item in items:
print(item)
# Loop through each key and it's index in a list
for item in items:
print items.index(item),item
# Loop through each key in a dictionary
for eachthing in inventory:
print(eachthing)
# Loop through each value in a dictionary
for eachthing in inventory:
print(inventory[eachthing])
# Loop through each key and value in a dictionary
for eachthing in inventory:
print(eachthing,inventory[eachthing])
# With numbers
numbers = [3,53,534,2253]
for number in numbers:
print(number/2.0)
# A list comprehension is a for loop (comming up)
half=[number/2.0 for number in numbers]
print(half)
Booleans: On and Off
Functions (Work In Progress)
# Arguments & Parameters
# An argument is a variable that can be put into a function
# The things going in are called arguments, and the thing(s) they go into are the parameters
# a and b are the paremeters and 2 and 4 are the arguments.
def sum(a,b):
print(a+b)
print(sum(2,4))
# Return
def product(a,b):
return a*b
print(product(3,4))
# Lambda
x = lambda a,b: a+b
print(x(6,8))
# Local and Global Variables
world = 'BIG'
def change():
# get the global variable
global world
# change it
world = 'small'
# You have to all the function to chagne it.
change()
print(world)
# Argument Parameters (Spell check)
# Putting a star in front of the parameter allows a variable amount of arguments
def display(*x):
print(x)
display(1,2,3,4,True,"Nothing")
# Keyword Arguments
# Pass variable amounts of key-value pairs to a function
def info(**information):
return information
gathered_info=info(name="Tutorial Doctor",age=29,height=6.3,cool=True)
print gathered_info['name']
# Named Arguments (for clarity on input)
def Info(name='',age=0):
return(name,age)
print(Info(age=45,name='Joe'))
# Generators
# A python generator is used to give a function return multiple values
def F():
yield 1
yield 2
f = F()
f.next()
print f.next()
# Built In
# Execute string as code
code = "print('Hello user...')"
exec(code)
#Execute a file in the directory of
#execfile('script.py') #file must exist of course, so create it
# Convert integer to a binary string
print(bin(64))
YIELD
def Generator():
print('Start Generator..')
yield "Hello"
yield "World"
yield ".."
print('End Generator')
for value in Generator():
print(value)
List Comprehension
numbers = [1,2,3,4,5,6,7,8,9]
squares = [x*x for x in numbers]
print(squares)
# Read as: squares equals x times x for every item x in numbers
# Alternately read as: for x in numbers, x equals x squared (set that to squares)
# More pythonic:
cubes = [number**3 for number in numbers]
print(cubes)
# With text
names = ["Python","Ruby","C","Javascript"]
prefixed_names = ["Language: " + name for name in names]
print(prefixed_names)
DOCSTRINGS
def display():
# A doctstring is a string that documents what the function does
"This function displays something"
print(display.__doc__)
File Handling
# Files work like notebooks
# It has to have a name
file_name = "notebook.txt"
# You have to open it
# If you want to write in it, you have to use the w mode
notebook = open(file_name,'w+')
# Then you write in it
notebook.write("Writing in my notebook")
# Writing something else into it
notebook.write(" again")
# When you are finished, you have to close it
notebook.close()
# Next time you want to open it for reading (r mode)
file_content=open(file_name,'r')
# Then you read it
print(file_content.read())
# The files are created in the same directory as the script
# Modes
WRITE = 'w'
READ = 'r'
APPEND = 'a'
READWRITE = 'w+'
# Another way (automatically closes the file and handles errors)
with open('spiral_notebook.txt',mode=WRITE) as spiral_notebook:
spiral_notebook.write('This is my spiral notebook')
with open('spiral_notebook.txt',mode=READ) as spiral_notebook:
print(spiral_notebook.read())
Decorators
A function that calls a function?
DATA MODELS
class Coin(object):
def __init__(self,val):
self.value=val
def __str__(self):
return str(self.value)
def __cmp__(self,other):
return self.value #Work In Progress (for comparisons)
def __add__(self,other):
return self.value+other.value
def __mul__(self,other):
return self.value*other.value
def __div__(self,other):
return self.value/other.value
def __sub__(self,other):
return self.value-other.value
def __len__(self):
return self.value
def __contains__(self,item):
pass #Work In Progress (for in statement)
def __call__(self):
print('You called me?')
print(self.__class__.__name__)
penny = Coin(1)
nickle = Coin(5)
dime = Coin(10)
quarter = Coin(25)
print(quarter-dime)
print(dime*nickle)
print(penny+quarter)
print(quarter/nickle)
penny()
print str(len(penny)) + ' is my value'
Parsing CSV
WRITE = 'w'
READ = 'r'
APPEND = 'a'
READWRITE = 'w+'
csv_notebook_name = "csv_notebook.csv"
csv_notebook = open(csv_notebook_name,mode=WRITE)
#Yeah you can do that
csv_notebook.write("name,Raphael,")
csv_notebook.write("age,29,")
csv_notebook.close()
content = open(csv_notebook_name,'r')
print(content.read())
Date and Time
Remove clipboard and console import if you aren't using Pythonista
import datetime
time_stamp = datetime.datetime.today().strftime('%m_%d_%Y_%H_%M_%S')
# Pythonista(IOS) only:
#clipboard.set(time_stamp)
print('Timestamp added to clipboard ') + time_stamp
today = datetime.datetime.today()
print(today.month,today.day,today.year,today.hour,today.minute,today.second)
month = today.strftime('%B')
print(month)
day = today.strftime('%A')
print(day)
# Pythonista(IOS) only:
# console.hud_alert('Timestamp added to clipboard '+ time_stamp,duration=1)
#%b month abbreviation
#%B full month name
#%m two digit month
#%y two digit year
#%Y four digit year
#%a day of the week abbreviation
#%A day of the week
#%d date
#%M minutes
#%S two dogit seconds
#%H two digit hour
re - Pattern Matching
import re
# Find all expressions/patterns in the email and print the matches
email = 'jacob&suzie#12@gmail.com'
expression = '^j.+'
matches = re.findall(expression,email)
print(matches)
# Find all extensions
extensions = '\.\w{3}'
extensions = re.findall(extensions,email)
print(extensions)
# Find all numbers
numbers = '\d+'
numbers = re.findall(numbers,email)
print(numbers)
# Find these symbols
symbols = '[@#&]'
symbols = re.findall(symbols,email)
print symbols
ZipFile - Compression
from zipfile import ZipFile
# Zip files work lile regular files
#Modes
READ= 'r'
WRITE='w'
APPEND = 'a'
UNIVERSAL = 'U'
UNIVERSAL_READLINE = 'rU'
# We will put a notebook into a zipped backpack (the analogy)
# Write inside of the notebook
with open('Notebook.txt','w') as outfile:
outfile.write('This is my language arts notebook')
# Write a file to a zip file
# Put the notebook in the backpack
with ZipFile('backpack.zip', 'w') as myzip:
myzip.write('Notebook.txt')
# Extract all files in a zip file into another directory
# Take everything out of the backpack and put it on a desk
with ZipFile('backpack.zip') as mzip:
mzip.extractall('Desk')
# Read a zip file
# Read something from the backpack
with ZipFile('backpack.zip','r') as mzip:
print mzip.open('Notebook.txt','r').read()
copy
None
pickle
None
os
import os
# Get current working directory (returns the path to the current folder)
print(os.getcwd())
this_directory=os.getcwd()
# Create a directory/folder in a path
try:
new_directory = os.mkdir(this_directory+'/New Folder')
print('Directory created.')
except:
print('Directory already exists.')
# Create multiple directories
try:
os.makedirs(this_directory+'/Folder1/Folder2/Folder3')
print('Directories created.')
except:
print('Those directories already exist.')
# Change the current directory/folder to a path
#os.chdir() ?
# Remove a directory
#os.rmdir(path) ?
# Move up or down a path
# print os.walk() ?
# directory of a file
#Remove path
# os.remove()
# os.remove(new_directory+'/a.txt')
socket
None
json
import json
webbrowser
import webbrowser
url = 'editorial://open/new.txt'
webbrowser.open(url)
urllib
import urllib
pydoc
import pydoc
# Locate path to a library
print(pydoc.locate('urllib'))
# Print/render documentation on a module
print(pydoc.render_doc('str'))
# Import a module
print(pydoc.importfile('lambda.py'))
# Turn documentation on a module into html
# File stored in directory of the script
print(pydoc.writedoc('str'))
# more uses coming...
lib2to3
None
timeit
# Time small bits of code (execution time)
import timeit
code = "print('Hello World')"
print timeit.timeit(code,number=1)
# takes about .033 seconds on average
# Time a Custom function
def add(a,b):
print a+b
print(timeit.timeit("add(2,4)", setup="from __main__ import add",number=1))
Tokenize
# Tokenization is the task of chopping a sequence up into pieces, called tokens. You can tokenize a string. The split() function tokenized strings. Tokens arent repeated.
word = 'red/blue'
split_word = word.split('/') # / is the delimiter
# A delimiter is a boundary between parts(usually punctuation)
print(split_word)
word2 = "brother's"
split_word_2 = word2.split("'")
print(split_word_2)
import tokenize
POPULAR MODULES
datetime
re
copy
pickle
os
socket
json
webbrowser
urllib
pydoc
lib2to3
timeit
Error Handling
begin
# code that may raise an exception
puts x
rescue
# code to handle the exception
puts 'Rescuing the error that occurred'
end
:::