This document provides an introduction to Ruby and Ruby on Rails. It discusses Ruby's philosophy of being a programming language for human beings that emphasizes expressive code. It also covers Ruby's community and popular frameworks like Ruby on Rails. The document then demonstrates various Ruby classes and control structures through examples in Pry, Ruby's interactive shell, including strings, symbols, numbers, ranges, dates, arrays, hashes, procs and lambdas. Exercises are provided to practice working with these Ruby concepts.
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Introduction to Ruby & Ruby on Rails
1. Introduction to Ruby & Ruby on Rails
Marcelo Correia Pinheiro
http://salizzar.net - @salizzar - https://github.com/salizzar
Wednesday, October 2, 13
2. More one programming language?
Maybe, depends on you
Today, knowledge of compiled /
bytecoded / interpreted programming
languages are requirements in market
to programmers that wants to work in
*nice real world*
“A language that doesn’t affect the way
you think about programming, is not
worth knowing.” Perlis, Alan (ALGOL)
wat
Wednesday, October 2, 13
3. Tell me more
Ruby is a general-purpose Object-Oriented Programming language.
But we can consider it as a “hybrid language”, due for their functional-
paradigm support
Created by Yukihiro Matsumoto (aka Matz) in Japan, 1995
Heavily inspired on Smalltalk with some flavor of Eiffel, Lisp, Python and
others
Current version: 2.0
Wednesday, October 2, 13
4. Ruby Philosophy
“A programming language for human beings”.
Expressive code
Powerful expansion by Metaprogramming / Functional Paradigm
Make programming more fun
Be productive
Wednesday, October 2, 13
5. Ruby Community
One of most innovative and active today:
Ruby on Rails
TDD / BDD, Configuration Management
A LOT of libraries that inspired other communities (Python, Go, Java, C# etc)
Has created other Virtual Machine implementations (default is MRI):
JRuby (runs on JVM)
Rubinius (written in C++ with LLVM)
Maglev (written in Smalltalk)
RubyMotion (runs on iOS and OSX)
Wednesday, October 2, 13
6. Who uses Ruby
On Planet Earth:
Twitter (meh)
NASA
Google
Groupon
Github
A lot of startups
Wednesday, October 2, 13
7. Who uses Ruby
In HUEland:
Locaweb
Globo.com
UOL
Abril
A lot of startups
Wednesday, October 2, 13
8. Time to code
In this keynote, we will see:
IRB (Interactive Ruby Shell)
Flow Control Mechanisms
Ruby Main Classes
Classes, Modules and Mix-ins
Some Ruby STDLIB classes
Ruby Libraries
Wednesday, October 2, 13
9. IRB (Interactive Ruby Shell)
Many dynamic languages offers a shell for fun and learn, Ruby too
Shipped version is better than otthers REPL shells
Just type in your terminal:
$ irb
Wednesday, October 2, 13
10. IRB (Interactive Ruby Shell)
Is very nice, but...
Let’s look at pry, an improvement to irb:
$ pry
[1] pry(main)> def hello(fella)
[1] pry(main)* puts "Hello, #{fella}! :)"
[1] pry(main)* end
=> nil
[2] pry(main)> hello 'marcelo'
Hello, marcelo! :)
=> nil
Wednesday, October 2, 13
11. Flow Control Mechanisms
if / else
[1] pry(main)> require 'date'
=> true
[2] pry(main)> condition = Date.today.sunday?
=> true
[3] pry(main)> if condition then
[3] pry(main)* puts 'condition is true'
[3] pry(main)* else
[3] pry(main)* puts 'condition is false'
[3] pry(main)* end
condition is true
=> nil
[4] pry(main)> puts 'condition is true' if condition
condition is true
=> nil
Wednesday, October 2, 13
12. Flow Control Mechanisms
unless / else
[1] pry(main)> require 'date'
=> true
[2] pry(main)> condition = Date.today.monday?
=> false
[3] pry(main)> unless condition then
[3] pry(main)* puts 'condition is false'
[3] pry(main)* else
[3] pry(main)* puts 'condition is true'
[3] pry(main)* end
condition is false
=> nil
[4] pry(main)> puts 'condition is false' unless condition
condition is false
=> nil
Wednesday, October 2, 13
13. Flow Control Mechanisms
while
[1] pry(main)> i = 1
[2] pry(main)> while i <= 3
[2] pry(main)* puts i ; i += 1
[2] pry(main)* end
1
2
3
[3] pry(main)> i = 1
[4] pry(main)> begin
[4] pry(main)* puts i ; i += 1
[4] pry(main)* end while i <= 3
1
2
3
Wednesday, October 2, 13
14. Flow Control Mechanisms
until
[1] pry(main)> i = 1
[2] pry(main)> until i > 3
[2] pry(main)* puts i ; i += 1
[2] pry(main)* end
1
2
3
[3] pry(main)> i = 1
[4] pry(main)> begin
[4] pry(main)* puts i ; i += 1
[4] pry(main)* end until i > 3
1
2
3
Wednesday, October 2, 13
15. Flow Control Mechanisms
for each
[1] pry(main)> for i in (1..3)
[1] pry(main)* puts i
[1] pry(main)* end
1
2
3
[2] pry(main)> (1..3).each do |i|
[2] pry(main)* puts i
[2] pry(main)* end
1
2
3
Wednesday, October 2, 13
17. Before coding, remember
It’s all about OOP.
Everything is object (strings, numbers etc)
All objects are passed by reference in method calls
Object communicates themselves by message exchange (Smalltalk
philosophy)
Wednesday, October 2, 13
19. Ruby Main Classes: String
So. Simple. No. Mistery.
As all Ruby Core classes, contains a lot of useful methods for mundane-
daily-manipulation
Wednesday, October 2, 13
21. Ruby Main Classes: String
Exercise 01: given a string, loop inside their chars and output respective
char and ASCII code
Tip #1: ‘c’.ord returns ASCII code
Tip #2: string[i] returns respective char in string (default index is 0)
Tip #3: to print string, puts string[i].ord
Wednesday, October 2, 13
22. Ruby Main Classes: Symbol
Symbols are strings that are stored as unique identifiers in memory
In other words, when you create a symbol and uses it in your program,
all references to these symbol appoints to same instance while
application is running
Wednesday, October 2, 13
23. Ruby Main Classes: Symbol
[1] pry(main)> symbol = :HUEland
=> :HUEland
[2] pry(main)> symbol.object_id
=> 677228
[3] pry(main)> :HUEland.object_id
=> 677228
Wednesday, October 2, 13
24. Ruby Main Classes: Fixnum
Well-known as Integer, but with some differences
Ruby stores numbers in memory based on machine architecture (native
machine word - 1 byte)
If a number is insanely big and exceeds upper and lower bounds, is
converted to a Bignum automagically
Wednesday, October 2, 13
26. Ruby Main Classes: Fixnum
Exercise 02: write a Fibonacci method with recursion
Wednesday, October 2, 13
27. Ruby Main Classes: Bignum
As name says, a <censored> big
number
It’s like Higgs Boson particle on
daily programming, nobody has
ever seen
Wednesday, October 2, 13
29. Ruby Main Classes: Range
Believe me: is a range. (meh)
You don’t need to create arrays of
indexes [ 1..5 ] or create famous
“i” variables to be used in a while
loop, just use (1..5).each
Wednesday, October 2, 13
30. Ruby Main Classes: Range
[1] pry(main)> range = (1..3)
=> 1..3
[2] pry(main)> range.each { |i| puts i }
1
2
3
=> 1..3
[3] pry(main)> range.reverse_each { |i| puts i }
3
2
1
=> 1..3
Wednesday, October 2, 13
31. Ruby Main Classes: Range
Exercise 03: From 1 to 100, print number and if is prime
Tip: use the following method
If is strange, don’t worry; you will understand it soon :)
def prime?(x)
(2 .. Math.sqrt(x)).each { |n| return false if x % n == 0 }
true
end
Wednesday, October 2, 13
32. Ruby Main Classes: Float
A float (O’RLY?)
As all Ruby classes, contains
some interesting methods (RTFM)
Wednesday, October 2, 13
34. Ruby Main Classes: Date
Meh.
Support for Julian Calendar and
other RFC methods
Support arithmetical operations
with integers and other types
Wednesday, October 2, 13
36. Ruby Main Classes: Time
Date with time (hour, minutes and seconds)
IMPORTANT: Ruby have two Time implementations:
A class from Core, that have a lot of methods
A module from STDLIB that contains parsing feature and other
methods
Wednesday, October 2, 13
37. Ruby Main Classes: Time
1] pry(main)> now = Time.now
=> 2013-09-21 13:35:24 -0300
[2] pry(main)> require 'time'
=> true
[3] pry(main)> now = Time.parse "#{Date.today} #{Time.now.strftime "%H:%M:%S"}"
=> 2013-09-21 13:36:13 -0300
Wednesday, October 2, 13
38. Ruby Main Classes: Array
Meh.
A LOT of useful methods like
select, collect, reverse, sort and
others
Accepts anything (numbers,
strings, constants etc)
Wednesday, October 2, 13
40. Ruby Main Classes: Array
Exercise 04: From 1 to 100, store prime numbers in a array
Tip: use previous exercise to help
Wednesday, October 2, 13
41. Ruby Main Classes: Hash
A dictionary (O’RLY?)
Shares same behavior of Array,
accepts anything as keys/values
You can do some fun routines
with it
Wednesday, October 2, 13
43. Ruby Main Classes: Hash
Exercise 05: From 1 to 100, stores in a hash the last digit of a prime
number as a key and value inside a array
Wednesday, October 2, 13
44. Ruby Main Classes: Proc
Time to get real fun.
Ruby is a hybrid language, right? YES
Let’s talk about some Computation
Theory
First-class citizens
Anonymous functions
Closures & Blocks
Wednesday, October 2, 13
45. Ruby Main Classes: Proc
In Ruby, as documentation says:
“Proc objects are blocks of
code that have been bound to a
set of local variables. Once
bound, the code may be called
in different contexts and still
access those variables.”
Wednesday, October 2, 13
47. Ruby Main Classes: Lambda
Lambda is a Proc, with
*important* differences
A lambda checks arity of
arguments passed
return keyword behaves
differently compared to Proc
instances
Wednesday, October 2, 13
48. Ruby Main Classes: Lambda
[1] pry(main)> def get_a_lambda(fella)
[1] pry(main)* ret = lambda { return "Lambda hello, #{fella}" }
[1] pry(main)* ret.call
[1] pry(main)* "#{fella}, you will see this message"
[1] pry(main)* end
=> nil
[2] pry(main)> def get_a_proc(fella)
[2] pry(main)* ret = Proc.new { return "Proc hello, #{fella}" }
[2] pry(main)* ret.call
[2] pry(main)* "#{fella}, you will never see this message"
[2] pry(main)* end
=> nil
[3] pry(main)> get_a_lambda('Marcelo')
=> "Marcelo, you will see this message"
[4] pry(main)> get_a_proc('Marcelo')
=> "Proc hello, Marcelo"
Wednesday, October 2, 13
49. Ruby Main Classes: Lambda
Exercise 06: rewrite Fibonacci method as a lambda
Wednesday, October 2, 13
50. Ruby Main Classes: Regexp
Regular Expressions (O’RLY?)
If you never heard about it... don’t
worry, the day that you need to
extract some text patterns in log
files will come
Wednesday, October 2, 13
51. Ruby Main Classes: Regexp
[1] pry(main)> message = "Gooby pls xow em de code"
=> "Gooby pls xow em de code"
[2] pry(main)> a_pattern = /gooby/i
=> /gooby/i
[3] pry(main)> another = Regexp.new('pls xow em de code')
=> /xow em de code/
[4] pry(main)> message.gsub(a_pattern, 'Dolan').gsub(another, 'you shall not pass')
=> "Dolan you shall not pass"
Wednesday, October 2, 13
52. Ruby Main Classes: Regexp
You know how use it, let’s gonna exercise with a LIVE example replacing
all occurrences of aeiou with *
Wednesday, October 2, 13
53. Ruby Classes
OK, Ruby seems to be cool. How I start to create some classes?
Let’s revisit inheritance and polymorphism.
Ruby have public, protected and private accessors
Ruby not have abstract classes and interfaces
Ruby not supports multiple inheritance, but with Modules we can
provide it (Mix-ins)
Wednesday, October 2, 13
54. Ruby Classes
[1] pry(main)> class GeometricShape
[1] pry(main)* def get_area
[1] pry(main)* raise NotImplementedError.new
[1] pry(main)* end
[1] pry(main)* end
=> nil
[2] pry(main)> wat = GeometricShape.new
=> #<GeometricShape:0x0000000257dc10>
[3] pry(main)> wat.get_area
NotImplementedError: NotImplementedError
from (pry):3:in `get_area'
Wednesday, October 2, 13
57. Ruby Classes
Exercise 07: create a Trapezium class that extends GeometricShape and
write get_area method
Wednesday, October 2, 13
58. Ruby Modules / Mix-ins
Modules are a fragment of code
(methods, other classes, constants etc)
that we can include:
In classes
In other modules
We use to create namespaces too
In Ruby, we call action of including a
Module inside a class / other module
as Mix-in
Wednesday, October 2, 13
59. Ruby Modules / Mix-ins
[1] pry(main)> module GUI
[1] pry(main)* module Renderer
[1] pry(main)* def render
[1] pry(main)* "Rendering #{self.class.name} with Area #{self.get_area}... done"
[1] pry(main)* end
[1] pry(main)* end
[1] pry(main)* end
=> nil
[2] pry(main)> class Square
[2] pry(main)* include GUI::Renderer
[2] pry(main)* end
=> Square
[3] pry(main)> class Triangle
[3] pry(main)* include GUI::Renderer
[3] pry(main)* end
=> Triangle
Wednesday, October 2, 13
61. Ruby STDLIB Classes
Ruby provides *a lot* of useful classes
Check ruby-doc.org before starting
to code, maybe it is shipped :)
We will see the following:
Net::HTTP
Benchmark
Test::Unit
Wednesday, October 2, 13
62. Ruby STDLIB Classes: Net::HTTP
A HTTP client to GET, POST, PUT and DELETE
HTTPS Support
Interface not so good, but community has created other libraries that
encapsulates calls in a better way
Wednesday, October 2, 13
63. Ruby STDLIB Classes: Net::HTTP
[1] pry(main)> require 'net/http'
=> true
[2] pry(main)> response = Net::HTTP.get(URI('http://www.terra.com.br'))
=> "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">n<html><head>n<title>301 Moved
Permanently</title>n</head><body>n<h1>Moved Permanently</h1>n<p>The document has moved <a href=
"/portal/">here</a>.</p>n</body></html>n"
[3] pry(main)> hash = {}
=> {}
[4] pry(main)> response.chars.each do |c|
[4] pry(main)* hash[c.to_s] = hash[c.to_s].nil? ? 1 : hash[c.to_s] + 1
[4] pry(main)* end
=> "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">n<html><head>n<title>301 Moved
Permanently</title>n</head><body>n<h1>Moved Permanently</h1>n<p>The document has moved <a href=
"/portal/">here</a>.</p>n</body></html>n"
[5] pry(main)> hash.keys.sort.each do |k|
[5] pry(main)* puts "'#{k}' = #{hash[k]}"
[5] pry(main)* end
=> (... a big input here ...)
Wednesday, October 2, 13
64. Ruby STDLIB Classes: Net::HTTP
Exercise 08: stores in a Hash all occurrences of chars given a URL that is
called using Net::HTTP
Wednesday, October 2, 13
65. Ruby STDLIB Classes: Benchmark
Benchmark provides a way to
measure your code based on
elapsed execution time
A need-to-know to check
algorithm efficiency
Wednesday, October 2, 13
66. Ruby STDLIB Classes: Benchmark
[1] pry(main)> def fibonacci(x)
[1] pry(main)* return x if [ 0, 1 ].include?(x)
[1] pry(main)* fibonacci(x - 1) + fibonacci(x - 2)
[1] pry(main)* end
=> nil
[2] pry(main)> fib = lambda do |x|
[2] pry(main)* return x if [ 0, 1 ].include?(x)
[2] pry(main)* fib[x - 1] + fib[x - 2]
[2] pry(main)* end
=> #<Proc:0x000000029ec710@(pry):14 (lambda)>
[3] pry(main)> fibh = lambda do |x|
[3] pry(main)* return x if [ 0, 1 ].include?(x)
[3] pry(main)* Hash.new { |hash, n| hash[n] = n < 2 ? n : hash[n - 1] + hash[n - 2] }[x]
[3] pry(main)* end
=> #<Proc:0x000000031217d8@(pry):18 (lambda)>
Wednesday, October 2, 13
67. Ruby STDLIB Classes: Benchmark
[4] pry(main)> require 'benchmark'
=> true
[5] pry(main)> Benchmark.bm(15) do |b|
[5] pry(main)* b.report('fibonacci') { fibonacci(32) }
[5] pry(main)* b.report('fib') { fib.call(32) }
[5] pry(main)* b.report('fibh') { fibh.call(32) }
[5] pry(main)* end
user system total real
fibonacci 1.890000 0.000000 1.890000 ( 1.888704)
fib 2.700000 0.000000 2.700000 ( 2.697208)
fibh 0.000000 0.000000 0.000000 ( 0.000056)
Wednesday, October 2, 13
68. Ruby STDLIB Classes: Test::Unit
Test. Your. Code.
If you never heard before about this,
seriously... LEARN.
Helps to create better software
No fear while refactoring
Check possible problems in future
Increases application design over
time
Wednesday, October 2, 13
69. Ruby STDLIB Classes: Test::Unit
# 01_fibonacci.rb
def fibonacci(x)
return x if x == 0 || x == 1
fibonacci(x - 1) + fibonacci(x - 2)
end
Wednesday, October 2, 13
70. Ruby STDLIB Classes: Test::Unit
require './01_fibonacci'
require 'test/unit'
class TestFibonacci < Test::Unit::TestCase
def test_fib
assert_equal(fibonacci(0), 0)
assert_equal(fibonacci(1), 1)
assert_equal(fibonacci(10), 55)
end
end
Wednesday, October 2, 13
72. Ruby STDLIB Classes: Test::Unit
For given exercises, write test FIRST :)
Exercise 09: write a TestCase for 2 + 2
Exercise 10: write a TestCase that asserts that our prime method is
correct for 4 scenarios
Tip: use assert_equal
Wednesday, October 2, 13
73. Ruby Libraries
A Ruby Library is called a Gem.
Ruby community has created a canonical
repository: Rubygems.org
Create a library is easy, anyone can create
and share in repo; but:
Cover with tests first;
Make it more generic as possible;
NO MONKEY PATCHES* (until you
know what you do)
Wednesday, October 2, 13
74. Ruby Libraries
Ruby have a tool to map dependencies
and install/vendorize gems: bundler
It requires a Gemfile, a file that we add
all required gems to application work
Great advantage: we can ship a Ruby
app with all dependencies inside it
Of course, if we use native gems then
the destination must have the same
OS & architecture (x86, x86_64)
Wednesday, October 2, 13
75. Ruby Libraries
Time to show how create a Ruby application from zero using bundler.
Wednesday, October 2, 13
76. Ruby on Rails
A little introduction
Wednesday, October 2, 13
77. Ruby on Rails: wat
A framework to create web applications.
Created by David Heinemeier Hansson (aka @dhh), Denmark 2004
David was attended in FISL 2005 as a speaker to show RoR
Apple was shipped RoR in 2007 in OSX Leopard
Wednesday, October 2, 13
78. Ruby on Rails: !hype
Why Rails is so important?
RoR was the first web framework that effectively works well
Microsoft tried to resolve with first version of Microsoft.NET ASP.NET,
but create a state persistence in a stateless protocol (HTTP) was failed
as hell (ASPNET hidden fields storing >= 128Kb *zipped* strings)
Apache Struts works, but be ready to immerse in dozens of XML
configuration files to create a simple Hello World
Wednesday, October 2, 13
79. Ruby on Rails: Follow my rules
Ruby on Rails is a great example of opinionated software.
Convention over Configuration
Principle of Least Astonishment
KISS (Keep It Simple, Stupid)
DRY (Don’t Repeat Yourself)
Wednesday, October 2, 13
80. Ruby on Rails: Architecture
Rails is a MVC (Model-View-Controller) framework.
Model: main business rules and persistence
View: presentation layer of data
Controller: a bridge between models and views, based on actions
Wednesday, October 2, 13
81. Ruby on Rails: Models
Models are classes that maps entities in a database
Models uses ActiveRecord pattern to perform CRUD (Create / Read /
Update / Destroy) operations
Rails provides a agnostic interface to query in database with your
models
In other words, you don’t need to write SQL commands
Wednesday, October 2, 13
82. Ruby on Rails: Models
Rails have support for principal RDBMS’s on market
MySQL, PostgreSQL
Microsoft SQL Server, Oracle Database
Rails supports NoSQL Databases very, very well:
CouchDB, MongoDB
Cassandra, Redis
Wednesday, October 2, 13
83. Ruby on Rails: Models
Models contains a set of useful validations
Numeric
Regular Expression
Inclusion
Value is blank
etc
Wednesday, October 2, 13
84. Ruby on Rails: Views
Views are the presentation layer of data.
In Rails, views are fragments of HTML code that will be parsed /
executed by the render engine to stream pure HTML to client
Default render engine: ERB
But you can choice others:
Markdown, HAML
Wednesday, October 2, 13
85. Ruby on Rails: Controllers
Controllers are the man-in-the-middle of Models and Views.
Responsible to receive view data (HTML forms sent by POST/PUT/
DELETE) and create Model instances, orchestrate application logic
They *must* be little (tiny controllers, tiny models)
Are a entity that responds to a route
Wednesday, October 2, 13
86. Ruby on Rails: Routes
To talk about routes, we must revisit or know what is REST.
An approach to handle resources based on HTTP verbs in WWW
GET /resource -> READ
POST /resource -> CREATE
PUT /resource -> UPDATE
DELETE /resource -> DELETE
We can talk per hours here, but learn by yourself. It is a requirement today.
Wednesday, October 2, 13
87. Ruby on Rails: Migrations
When we need to create a entity in database, commonly a SQL script is
written to a DBA run it in a server.
With Migrations, we can create it without write any SQL script
Previous migrations are stored in database in order to avoid multiple
executions (ex: run a CREATE TABLE of a already existent table)
Wednesday, October 2, 13
88. Ruby on Rails: It’s showtime
Let’s try to create a blog engine (OH NO, AGAIN!)
Wednesday, October 2, 13