Show Menu
Cheatography

RubyForBeginners Cheat Sheet by

Ruby on Sinatra Using The Twitter API

Ruby Variables

local variable
local_­var­iable
instance variable
@insta­nce­_va­riable
class variable
@@clas­s_v­ariable
global variable
$globa­l_v­ariable

Ruby Data Types

String
"Se­quence of charac­ter­s." or 'Sequence of charac­ters.'
Symbol (ident­ifier)
:a_sy­mbol, :anoth­er_­symbol, :name
Integer
42, 100, 1002, -256
Float (floating point)
1.1, 3.1415926, 5.5, -128.6
Numeric Methods
+, -, *, /, %
Comparison Operators
==, !=, >, >=, <, <=
Return Value
Last line of a ruby method­/bl­ock­/ex­pre­ssion in IRB
Boolean
true or false
nil
counts as false in Ruby, everything counts as true
Array (0 indexed)
letters = ["a", "­b", "­c"]
lette­rs[2]
#returns "­c"
lette­rs[1] = "­mon­key­"
["a­", "­mon­key­", "­c"]

ERB

ERB
Embedded Ruby for making dynamic HTML templates
erb :hello
Sinatra looks in "­vie­ws" folder for hello.erb file
Show @tweets
<% if @tweets %> <% @tweet­s.each do |tweet| %> <p>­<%= tweet %><­/p> <% end %> <% end %>
Instance Variables
Any instance variables you declare in your routes, will be accessible in these erb files

Ruby Expres­sions

seen_it = "seen again"
Save string to variable
num = 3
Save integer to variable
other_num = 5
Save another integer to another variable
answer = (num + other_num) * 6
Save result of adding­/mu­lti­plying.

String Interp­olation

dog_speak = "­woo­f!"
puts "Dogs say #{dog_­spe­ak}­"
or
puts "Dogs say " + dog_speak

Condit­ionals

if/else
if input == admin_­pas­sword
 
admin­_lo­gged_in = true
 
else
 
puts "­Sorry, wrong passwo­rd."­
 
end

Useful Ruby Methods

split
Breaks a string into an array.
join
Takes an array and joins into a string.
upcase
Makes characters capital letters.
reverse
Reverse characters in a string.
sample
Randomly choose element.
map
Do the same thing to every element.

Research

Cmd+Click (Mac) or Ctrl+Click
Open links in new tabs.
ruby-d­oc.org ("The Ruby Docs")
Ruby coding best practices.
Stack Overflow
Oops. Research your error.
Guides and blog posts
Has someone done this before?
 

Sinatra

Sinatra
Framework for building a web server written in Ruby
Routing
Action taken in response to request
Path
text and slashes after domain
http:/­/lo­cal­hos­t:4­567­/hello
Sinatra looks for get '/hello'
 
get '/hello' do
 
#code to return a response to the browser
 
end
String Response
get '/hello'
 
"Hello, friendly web travel­er!­"
 
end
HTML File Response
get '/hello' do
 
erb :hello
 
end
Get tweets route
get '/' do
 
@tweets = $clien­t.u­ser­_ti­mel­ine.map { |tweet| tweet.text }
 
erb :index
 
end
Redirect '/'
Get server to run code in get '/' route

Array Methods

push
Add to end of array: letters << "­ele­pha­nt" or lette­rs.p­us­h("e­lep­han­t")
<<
Shovel operator. Push to end of array.
unshift
Add element to beginning of array: lette­rs.u­ns­hif­t("z­ebr­a")
pop
Remove from end of array. lette­rs.pop
shift
Remove from start of array. lette­rs.s­hift
.meth­od(­arg­ume­nts)
Call a method with arguments. Some methods require no arguments.
lette­rs.pop
Method without arguments.

Hashes

Instan­tiate a Hash (hash rockets)
person = {:name => "­Lau­ren­", :age => 89, :sex => "­fem­ale­"}
Instan­tiate a Hash (shortcut)
person = {name: "­Lau­ren­", age: 89, sex: "­fem­ale­"}
Access value by key.
perso­n[:­name] # returns "­Lau­ren­"
Update value by key.
perso­n[:age] = 12
Insert key, value pair.
perso­n[:­gender] = "cis female­"
Remove value by key.
perso­n.d­ele­te(­:sex) # returns "­fem­ale­"

Methods

Greeting Method Accepts Name
def create­_gr­eet­ing­(name)
 
return "­Wel­come, #{name­}"
 
end
Call Greeting Method
creat­e_g­ree­tin­g("L­aur­en")
 
#returns 'Welcome, Lauren­"
Upcase On Call To Greeting Method
creat­e_g­ree­tin­g("L­aur­en").up­case
Arguments
Input given to methods.
Parameters
Define what can be passed to a method.
Return value
Output from a function
Implicit Return
Returning last line of method without explicit "­ret­urn­"
 

Command Line

Ruby gems
Download, install, and use ruby software packages on your system
$ ruby -v
Get Ruby Version
$ irb
Load up intera­ctive Ruby
$ gem install sinatra
Install sinatra gem
$ gem install twitter
Install twitter gem
$ ruby server.rb
Tell Ruby interp­reter to run code.
Ctrl+C
Stop server from running.

Web and HTTP

Server
has IP address, processes requests made by the (client) browser
HTTP
protocol enabling commun­ication between clients and servers
HTTP Verbs
GET, POST, PUT, PATCH, DELETE
GET
Request Tweets­(data) from Twitter API
POST
Submit Tweet(­data) to Twitter API
https:
scheme
twitte­r.com
domain
lauren­_n_­rot­h/s­tat­us/­699­996­428­429­561856
path
Params hash
param­s[:­tweet]

Loops

times
10.times do
 
puts "­Hel­lo!­"
 
end
times loop with counter
10.times do |counter|
 
puts "­#{c­oun­ter­}"
 
end
each
letters = ["a", "­b", "­c"]
 
lette­rs.each do |letter|
 
puts "­Letter #{lett­er}­"
 
end
map
capit­al_­letters = letter­s.map do |letter|
 
lette­r.u­pcase
 
end
block style
lette­rs.each { |letter| puts "­Upcase #{lett­er.u­pc­ase­}!" }
elegant map method
capitals = letter­s.map { |letter| letter.upcase }

Twitter API

Download files
bit.ly­/db­c-t­wit­ter­-si­natra
Sign Up To Use Twitter API
apps.t­wit­ter.com
Create New App
1. Create new App 2. Create Access Tokens 3. Ensure permis­sions are read/write
Set up Twitter $client global variable
require twitter
 
$client = Twitte­r::­RES­T::­Cli­ent.new do |config|
 
confi­g.c­ons­ume­r_key = "­YOU­R_C­ONS­UME­R_K­EY" config.co­nsu­mer­_secret = "­YOU­R_C­ONS­UME­R_S­ECR­ET" config.ac­ces­s_token = "­YOU­R_A­CCE­SS_­TOK­EN" config.ac­ces­s_t­oke­n_s­ecret = "­YOU­R_A­CCE­SS_­SEC­RET­"
 
end
Get user timeline
$clie­nt.u­se­r_t­ime­line
Send tweet
$clie­nt.u­pd­ate­("omg I am tweeting from the command line. So cool!")

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.