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
"­Seq­uence of charac­ter­s." or 'Sequence of charac­ters.'
Symbol (ident­ifier)
:a_symbol, :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"]
letters[2]
#returns "­c"
letters[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_­log­ged_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 letter­s.p­ush­("el­eph­ant­")
<<
Shovel operator. Push to end of array.
unshift
Add element to beginning of array: letter­s.u­nsh­ift­("ze­bra­")
pop
Remove from end of array. letter­s.pop
shift
Remove from start of array. letter­s.shift
.metho­d(a­rgu­ments)
Call a method with arguments. Some methods require no arguments.
letter­s.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.
person­[:name] # returns "­Lau­ren­"
Update value by key.
person­[:age] = 12
Insert key, value pair.
person­[:g­ender] = "cis female­"
Remove value by key.
person.de­let­e(:sex) # returns "­fem­ale­"

Methods

Greeting Method Accepts Name
def create­_gr­eet­ing­(name)
 
return "­Wel­come, #{name­}"
 
end
Call Greeting Method
create­_gr­eet­ing­("La­ure­n")
 
#returns 'Welcome, Lauren­"
Upcase On Call To Greeting Method
create­_gr­eet­ing­("La­ure­n").u­pcase
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
params­[:t­weet]

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"]
 
letter­s.each do |letter|
 
puts "­Letter #{lett­er}­"
 
end
map
capita­l_l­etters = letter­s.map do |letter|
 
letter.upcase
 
end
block style
letter­s.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|
 
config.co­nsu­mer_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
$clien­t.u­ser­_ti­meline
Send tweet
$clien­t.u­pda­te(­"omg I am tweeting from the command line. So cool!")
 

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.