SlideShare une entreprise Scribd logo
1  sur  64
Télécharger pour lire hors ligne
Ruby
Uma introdução
ÍGOR BONADIO
Origem
Criador
•  Yukihiro Matsumoto (Matz)
•  Japão, 1995
Criador	
  
•  Yukihiro Matsumoto (Matz)
•  Japão, 1995
“I wanted a scripting language that was
more powerful than Perl, and more
object-oriented than Python3.”
Matz [1]
[1]	
  h&p://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html	
  
Inspirações: Perl
class Robot
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
end
Inspirações: Perl
class Robot
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
end
Inspirações: Perl
class Robot
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
end
Inspirações: Smalltalk
1.next
# => 2
Robot.methods
# => [:walk_to, ...]
Inspirações: Smalltalk
1.next
# => 2
Robot.methods
# => [:walk_to, ...]
"I always knew one day Smalltalk would
replace Java. I just didn't know it would be
called Ruby.”
Kent Beck [2]
[2]	
  h&p://onsmalltalk.com/objects-­‐classes-­‐and-­‐constructors-­‐smalltalk-­‐style	
  
Inspirações: Lisp
[1, 2, 3].map {|n| n*2}
# => [2, 4, 6]
[1, 2, 3].reduce do |acc, n|
acc + n
end
# => 6
Ruby
•  Script
•  Interpretada
•  Tipagem forte e dinâmica
– Duck Typing
•  Orientada a objetos
•  Com características funcionais
Ruby + Ecossistema
•  RubyGems
•  Comunidade ativa
•  Diversos tutoriais
– Why (http://mislav.uniqpath.com/poignant-guide/)
•  Livros
– Programming Ruby (https://pragprog.com/book/ruby4/
programming-ruby-1-9-2-0)
– Metaprogramming Ruby (https://pragprog.com/book/
ppmetr2/metaprogramming-ruby-2)
Configurando e Conhecendo o
Ambiente
RVM
•  Gerencia diversas versões
– MRI (1.9.3, 2.2.3, etc)
– JRuby
– Rubinious
– MacRuby
– MagLev
RVM
$ curl -sSL https://get.rvm.io | bash -s stable
RVM
$ curl -sSL https://get.rvm.io | bash -s stable
$ rvm install 2.2.3
RVM
$ curl -sSL https://get.rvm.io | bash -s stable
$ rvm install 2.2.3
$ rvm use 2.2.3
Note que...
•  Ruby funciona muito bem em
– Linux
– OSX
– BSD
•  Mas não muito bem em Windows...
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 >
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 >
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
=> 3
2.2.0 :003 >
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
=> 3
2.2.0 :003 > "blah".u
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
=> 3
2.2.0 :003 > "blah".u
"blah".unicode_normalize "blah".untaint "blah".upcase!
"blah".unicode_normalize! "blah".untrust "blah".upto
"blah".unicode_normalized? "blah".untrusted?
"blah".unpack "blah".upcase
2.2.0 :003 > "blah".u
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
=> 3
2.2.0 :003 > "blah".u
"blah".unicode_normalize "blah".untaint "blah".upcase!
"blah".unicode_normalize! "blah".untrust "blah".upto
"blah".unicode_normalized? "blah".untrusted?
"blah".unpack "blah".upcase
2.2.0 :003 > "blah".upcase
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
=> 3
2.2.0 :003 > "blah".u
"blah".unicode_normalize "blah".untaint "blah".upcase!
"blah".unicode_normalize! "blah".untrust "blah".upto
"blah".unicode_normalized? "blah".untrusted?
"blah".unpack "blah".upcase
2.2.0 :003 > "blah".upcase
=> "BLAH"
2.2.0 :004 >
IRB
igorbonadio@marvin:~$ irb
2.2.0 :001 > 1 + 1
=> 2
2.2.0 :002 > 2.next
=> 3
2.2.0 :003 > "blah".u
"blah".unicode_normalize "blah".untaint "blah".upcase!
"blah".unicode_normalize! "blah".untrust "blah".upto
"blah".unicode_normalized? "blah".untrusted?
"blah".unpack "blah".upcase
2.2.0 :003 > "blah".upcase
=> "BLAH"
2.2.0 :004 > exit
Interpretador
$ ruby -e "puts 'Hello IME'"
Hello IME
Interpretador	
  
$ ruby -e "puts 'Hello IME'"
Hello IME
hello.rb	
  
puts	
  ‘Hello	
  IME’	
  
Interpretador	
  
$ ruby -e "puts 'Hello IME'"
Hello IME
$ ruby hello.rb
Hello IME
hello.rb	
  
puts	
  ‘Hello	
  IME’	
  
Gems	
  
$ gem install jeweler
$ gem list
*** LOCAL GEMS ***
addressable (2.3.7, 2.2.8)
backports (3.6.4)
bigdecimal (1.2.6)
blankslate (2.1.2.4)
builder (3.2.2)
...
A Linguagem
Declaração de Variáveis
name = "Ígor Bonadio"
NUMBER = 123
$os = "OSX"
Tudo é Objeto!
1.next # => 2
"blah".upcase # => "BLAH"
[1, 2, 3].size # => 3
Condicionais
if x < 3
comando1
comando2
else
outro_comando1
outro_comando2
outro_comando3
end
Laços
while x < 3
comando1
comando2
end
for x in [1, 2, 3]
puts x
end
Coleções
["osx", "linux", "windows"].each do |os|
puts "Sistema Operacional compatível: #{os}!"
end
# Sistema Operacional compatível: osx!
# Sistema Operacional compatível: linux!
# Sistema Operacional compatível: windows!
Coleções
%w(osx, linux, windows).each do |os|
puts "Sistema Operacional compatível: #{os}!"
end
# Sistema Operacional compatível: osx!
# Sistema Operacional compatível: linux!
# Sistema Operacional compatível: windows!
Funções
def sum(a, b)
a + b
end
sum(1, 2) # => 3
sum 4, 5 # => 9
Closures
def map(vector, &function)
resp = []
vector.each do |elem|
resp << function.call(elem)
end
resp
end
map([1,2,3]) do |x|
2*x
end
# => [2, 4, 6]
Closures
def map(vector, &function)
resp = []
vector.each do |elem|
resp << function.call(elem)
end
resp
end
map [1,2,3] do |x|
2*x
end
# => [2, 4, 6]
Strings vs Symbols
color_str = "Orange"
color_sym = :Orange
if color_str == "Blue"
# ...
end
if color_sym == :Blue
# ...
end
Classe
class Robot
def initialize(name)
@name = name
end
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
def self.build_evil_robot()
Robot.new("HAL")
end
end
Classe
class Robot
def initialize(name)
@name = name
end
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
def self.build_evil_robot()
Robot.new("HAL")
end
end
Classe
class Robot
def initialize(name)
@name = name
end
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
def self.build_evil_robot()
Robot.new("HAL")
end
end
Classe
class Robot
def initialize(name)
@name = name
end
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
def self.build_evil_robot()
Robot.new("HAL")
end
end
Classe
class Robot
def initialize(name)
@name = name
end
def walk_to(x, y)
@engine.turn_on
@engine.go_to(x, y, $map)
@engine.turn_off
end
def self.build_evil_robot()
Robot.new("HAL")
end
end
Duck Typing
class Robot
def walk_to(x, y)
#...
end
def bip()
#...
end
end
class Person
def walk_to(x, y)
#...
end
def talk(msg)
#...
end
end
def go_to(obj, x, y)
obj.walk_to(x, y)
end
def bip(obj)
obj.bip()
end
go_to(Robot.new, 1, 2) # ok
go_to(Person.new, 1, 2) # ok
bip(Robot.new) # ok
bip(Person.new) # error
Exemplos
QuickSort
def sort(array)
return array if array.size <= 1
pivot = array[0]
return sort(array.select { |y| y < pivot }) +
array.select { |y| y == pivot } +
sort(array.select { |y| y > pivot })
end
sort([1, 5, 6, 2, 4, 3])
# => [1, 2, 3, 4, 5, 6]
Getters & Setters
class Robot
def name
@name
end
def name=(n)
@name = n
end
def model
@model
end
def model=(m)
@model = m
end
#...
end
robot = Robot.new
robot.name = "HAL"
puts robot.name
Getters & Setters
class Robot
attr_accessor :name
attr_accessor :model
attr_accessor :color
attr_accessor :size
#...
end
robot = Robot.new
robot.name = "HAL"
puts robot.name
Getters & Setters	
  
class Accessor
def self.create_accessor(accessor_name)
define_method(accessor_name) do
instance_variable_get("@#{accessor_name}")
end
define_method("#{accessor_name}=") do |value|
instance_variable_set("@#{accessor_name}", value)
end
end
end
class Robot < Accessor
create_accessor :name
create_accessor :model
end
robot = Robot.new
robot.name = "HAL"
puts robot.name
Getters & Setters	
  
class Object
def self.create_accessor(accessor_name)
define_method(accessor_name) do
instance_variable_get("@#{accessor_name}")
end
define_method("#{accessor_name}=") do |value|
instance_variable_set("@#{accessor_name}", value)
end
end
end
class Robot < Accessor
create_accessor :name
create_accessor :model
end
robot = Robot.new
robot.name = "HAL"
puts robot.name
Getters & Setters	
  
class Object
def self.create_accessor(accessor_name)
define_method(accessor_name) do
instance_variable_get("@#{accessor_name}")
end
define_method("#{accessor_name}=") do |value|
instance_variable_set("@#{accessor_name}", value)
end
end
end
class Robot < Accessor
create_accessor :name
create_accessor :model
end
robot = Robot.new
robot.name = "HAL"
puts robot.name
Criando Métodos em Tempo de Execução
class Robot
def hello(name)
puts "Hello #{name}"
end
end
robot = Robot.new
robot.hello("IME")
# Hello IME
class Robot
def hello(name)
puts "Hello #{name}"
end
end
robot = Robot.new
robot.hello_ime
# => undefined	
  method	
  `hello_ime'	
  for	
  #<Robot:0x007ff3e9860c38>	
  (NoMethodError)
Criando Métodos em Tempo de Execução
class Robot
def hello(name)
puts "Hello #{name}"
end
def method_missing(method_name)
name = method_name.to_s.gsub("hello_", "")
hello(name.upcase)
end
end
robot = Robot.new
robot.hello_ime
# => Hello IME
robot.hello_igor
# => Hello IGOR
Criando Métodos em Tempo de Execução
Active Record	
  
class Group < ActiveRecord::Base
# ...
end
class Posts < ActiveRecord::Base
# ...
end
class User < ActiveRecord::Base
has_many :posts
belongs_to :group
end
user = User.find_by(name: 'Ígor Bonadio')
user.posts # => [...]
user.group.name # => IME
RSpec	
  
RSpec.describe User, :type => :model do
it "orders by last name" do
lindeman = User.create!(first_name: "Andy",
last_name: "Lindeman")
chelimsky = User.create!(first_name: "David”,
last_name: "Chelimsky")
expect(User.ordered_by_last_name).to eq([chelimsky,
lindeman])
end
end
Links Úteis
http://www.rubygems.org
https://www.ruby-toolbox.com

Contenu connexe

Tendances

(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Rolessartak
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Ben Pope
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helperslicejack
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails WorkshopAndre Foeken
 
An (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to PythonAn (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to PythonNicholas Tollervey
 
A Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageA Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageSmartLogic
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with MooseDave Cross
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQLCarlos Hernando
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Toolschrismdp
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012xSawyer
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介Wen-Tien Chang
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangSean Cribbs
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Andre Foeken
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaLin Yo-An
 

Tendances (20)

(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Getfilestruct zbksh(1)
Getfilestruct zbksh(1)
 
Advanced Shell Scripting
Advanced Shell ScriptingAdvanced Shell Scripting
Advanced Shell Scripting
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails Workshop
 
An (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to PythonAn (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to Python
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
A Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageA Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming Language
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with Moose
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQL
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 

En vedette

1st response Final presentation
1st response Final presentation1st response Final presentation
1st response Final presentationfloodprojects
 
ಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿ
ಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿ
ಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿFAHIM AKTHAR ULLAL
 
Hazrat khawaja ahmad mirvi no by anwar e raza
Hazrat khawaja ahmad mirvi no by anwar e razaHazrat khawaja ahmad mirvi no by anwar e raza
Hazrat khawaja ahmad mirvi no by anwar e razaMuhammad Tariq
 
Bimba kids teen - 25-08-2013
Bimba kids teen - 25-08-2013Bimba kids teen - 25-08-2013
Bimba kids teen - 25-08-2013Regina Lissone
 
Boletín de información ambiental
Boletín de información ambientalBoletín de información ambiental
Boletín de información ambientalCole Navalazarza
 
Kalraj MIshra Upcoming Future CM
Kalraj MIshra Upcoming Future CMKalraj MIshra Upcoming Future CM
Kalraj MIshra Upcoming Future CMsona dixit
 
Sagittarius - The Future of Search
Sagittarius - The Future of SearchSagittarius - The Future of Search
Sagittarius - The Future of SearchSagittarius
 
IT investment decision-making with confidence - A practical guide for medium-...
IT investment decision-making with confidence - A practical guide for medium-...IT investment decision-making with confidence - A practical guide for medium-...
IT investment decision-making with confidence - A practical guide for medium-...Girish Kumar Ayyappath
 
Tawanda glover presentation
Tawanda glover presentationTawanda glover presentation
Tawanda glover presentationttglover
 
Artes visuales examen dx est70_15-16
Artes visuales examen dx est70_15-16Artes visuales examen dx est70_15-16
Artes visuales examen dx est70_15-16Nitram Seyer
 

En vedette (15)

Nov 2012
Nov 2012Nov 2012
Nov 2012
 
1st response Final presentation
1st response Final presentation1st response Final presentation
1st response Final presentation
 
ಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿ
ಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿ
ಸಂಪತ್ತನ್ನು ಅನುಚಿತ ರೀತಿಯಲ್ಲಿ ಕಬಲಿಸಬೇಡಿರಿ
 
Hazrat khawaja ahmad mirvi no by anwar e raza
Hazrat khawaja ahmad mirvi no by anwar e razaHazrat khawaja ahmad mirvi no by anwar e raza
Hazrat khawaja ahmad mirvi no by anwar e raza
 
Bimba kids teen - 25-08-2013
Bimba kids teen - 25-08-2013Bimba kids teen - 25-08-2013
Bimba kids teen - 25-08-2013
 
Boletín de información ambiental
Boletín de información ambientalBoletín de información ambiental
Boletín de información ambiental
 
Articolo 18
Articolo 18Articolo 18
Articolo 18
 
Cct sandra cely - ruth
Cct sandra   cely - ruthCct sandra   cely - ruth
Cct sandra cely - ruth
 
Kalraj MIshra Upcoming Future CM
Kalraj MIshra Upcoming Future CMKalraj MIshra Upcoming Future CM
Kalraj MIshra Upcoming Future CM
 
SNT QUV TEST
SNT QUV TESTSNT QUV TEST
SNT QUV TEST
 
Sagittarius - The Future of Search
Sagittarius - The Future of SearchSagittarius - The Future of Search
Sagittarius - The Future of Search
 
IT investment decision-making with confidence - A practical guide for medium-...
IT investment decision-making with confidence - A practical guide for medium-...IT investment decision-making with confidence - A practical guide for medium-...
IT investment decision-making with confidence - A practical guide for medium-...
 
Tawanda glover presentation
Tawanda glover presentationTawanda glover presentation
Tawanda glover presentation
 
Marketing 4P's
Marketing 4P'sMarketing 4P's
Marketing 4P's
 
Artes visuales examen dx est70_15-16
Artes visuales examen dx est70_15-16Artes visuales examen dx est70_15-16
Artes visuales examen dx est70_15-16
 

Similaire à Ruby - Uma Introdução

Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is AwesomeAstrails
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?osfameron
 
Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Apoorvi Kapoor
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record.toster
 
Echtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLEchtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLMoritz Flucht
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1Jano Suchal
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worldsChristopher Spring
 

Similaire à Ruby - Uma Introdução (20)

Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 
Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Echtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLEchtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQL
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 

Dernier

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Dernier (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

Ruby - Uma Introdução

  • 3. Criador •  Yukihiro Matsumoto (Matz) •  Japão, 1995
  • 4. Criador   •  Yukihiro Matsumoto (Matz) •  Japão, 1995 “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python3.” Matz [1] [1]  h&p://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html  
  • 5. Inspirações: Perl class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end end
  • 6. Inspirações: Perl class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end end
  • 7. Inspirações: Perl class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end end
  • 8. Inspirações: Smalltalk 1.next # => 2 Robot.methods # => [:walk_to, ...]
  • 9. Inspirações: Smalltalk 1.next # => 2 Robot.methods # => [:walk_to, ...] "I always knew one day Smalltalk would replace Java. I just didn't know it would be called Ruby.” Kent Beck [2] [2]  h&p://onsmalltalk.com/objects-­‐classes-­‐and-­‐constructors-­‐smalltalk-­‐style  
  • 10. Inspirações: Lisp [1, 2, 3].map {|n| n*2} # => [2, 4, 6] [1, 2, 3].reduce do |acc, n| acc + n end # => 6
  • 11. Ruby •  Script •  Interpretada •  Tipagem forte e dinâmica – Duck Typing •  Orientada a objetos •  Com características funcionais
  • 12. Ruby + Ecossistema •  RubyGems •  Comunidade ativa •  Diversos tutoriais – Why (http://mislav.uniqpath.com/poignant-guide/) •  Livros – Programming Ruby (https://pragprog.com/book/ruby4/ programming-ruby-1-9-2-0) – Metaprogramming Ruby (https://pragprog.com/book/ ppmetr2/metaprogramming-ruby-2)
  • 14. RVM •  Gerencia diversas versões – MRI (1.9.3, 2.2.3, etc) – JRuby – Rubinious – MacRuby – MagLev
  • 15. RVM $ curl -sSL https://get.rvm.io | bash -s stable
  • 16. RVM $ curl -sSL https://get.rvm.io | bash -s stable $ rvm install 2.2.3
  • 17. RVM $ curl -sSL https://get.rvm.io | bash -s stable $ rvm install 2.2.3 $ rvm use 2.2.3
  • 18. Note que... •  Ruby funciona muito bem em – Linux – OSX – BSD •  Mas não muito bem em Windows...
  • 21. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 >
  • 22. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next
  • 23. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 >
  • 24. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u
  • 25. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u "blah".unicode_normalize "blah".untaint "blah".upcase! "blah".unicode_normalize! "blah".untrust "blah".upto "blah".unicode_normalized? "blah".untrusted? "blah".unpack "blah".upcase 2.2.0 :003 > "blah".u
  • 26. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u "blah".unicode_normalize "blah".untaint "blah".upcase! "blah".unicode_normalize! "blah".untrust "blah".upto "blah".unicode_normalized? "blah".untrusted? "blah".unpack "blah".upcase 2.2.0 :003 > "blah".upcase
  • 27. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u "blah".unicode_normalize "blah".untaint "blah".upcase! "blah".unicode_normalize! "blah".untrust "blah".upto "blah".unicode_normalized? "blah".untrusted? "blah".unpack "blah".upcase 2.2.0 :003 > "blah".upcase => "BLAH" 2.2.0 :004 >
  • 28. IRB igorbonadio@marvin:~$ irb 2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u "blah".unicode_normalize "blah".untaint "blah".upcase! "blah".unicode_normalize! "blah".untrust "blah".upto "blah".unicode_normalized? "blah".untrusted? "blah".unpack "blah".upcase 2.2.0 :003 > "blah".upcase => "BLAH" 2.2.0 :004 > exit
  • 29. Interpretador $ ruby -e "puts 'Hello IME'" Hello IME
  • 30. Interpretador   $ ruby -e "puts 'Hello IME'" Hello IME hello.rb   puts  ‘Hello  IME’  
  • 31. Interpretador   $ ruby -e "puts 'Hello IME'" Hello IME $ ruby hello.rb Hello IME hello.rb   puts  ‘Hello  IME’  
  • 32. Gems   $ gem install jeweler $ gem list *** LOCAL GEMS *** addressable (2.3.7, 2.2.8) backports (3.6.4) bigdecimal (1.2.6) blankslate (2.1.2.4) builder (3.2.2) ...
  • 34. Declaração de Variáveis name = "Ígor Bonadio" NUMBER = 123 $os = "OSX"
  • 35. Tudo é Objeto! 1.next # => 2 "blah".upcase # => "BLAH" [1, 2, 3].size # => 3
  • 36. Condicionais if x < 3 comando1 comando2 else outro_comando1 outro_comando2 outro_comando3 end
  • 37. Laços while x < 3 comando1 comando2 end for x in [1, 2, 3] puts x end
  • 38. Coleções ["osx", "linux", "windows"].each do |os| puts "Sistema Operacional compatível: #{os}!" end # Sistema Operacional compatível: osx! # Sistema Operacional compatível: linux! # Sistema Operacional compatível: windows!
  • 39. Coleções %w(osx, linux, windows).each do |os| puts "Sistema Operacional compatível: #{os}!" end # Sistema Operacional compatível: osx! # Sistema Operacional compatível: linux! # Sistema Operacional compatível: windows!
  • 40. Funções def sum(a, b) a + b end sum(1, 2) # => 3 sum 4, 5 # => 9
  • 41. Closures def map(vector, &function) resp = [] vector.each do |elem| resp << function.call(elem) end resp end map([1,2,3]) do |x| 2*x end # => [2, 4, 6]
  • 42. Closures def map(vector, &function) resp = [] vector.each do |elem| resp << function.call(elem) end resp end map [1,2,3] do |x| 2*x end # => [2, 4, 6]
  • 43. Strings vs Symbols color_str = "Orange" color_sym = :Orange if color_str == "Blue" # ... end if color_sym == :Blue # ... end
  • 44. Classe class Robot def initialize(name) @name = name end def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end def self.build_evil_robot() Robot.new("HAL") end end
  • 45. Classe class Robot def initialize(name) @name = name end def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end def self.build_evil_robot() Robot.new("HAL") end end
  • 46. Classe class Robot def initialize(name) @name = name end def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end def self.build_evil_robot() Robot.new("HAL") end end
  • 47. Classe class Robot def initialize(name) @name = name end def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end def self.build_evil_robot() Robot.new("HAL") end end
  • 48. Classe class Robot def initialize(name) @name = name end def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off end def self.build_evil_robot() Robot.new("HAL") end end
  • 49. Duck Typing class Robot def walk_to(x, y) #... end def bip() #... end end class Person def walk_to(x, y) #... end def talk(msg) #... end end def go_to(obj, x, y) obj.walk_to(x, y) end def bip(obj) obj.bip() end go_to(Robot.new, 1, 2) # ok go_to(Person.new, 1, 2) # ok bip(Robot.new) # ok bip(Person.new) # error
  • 51. QuickSort def sort(array) return array if array.size <= 1 pivot = array[0] return sort(array.select { |y| y < pivot }) + array.select { |y| y == pivot } + sort(array.select { |y| y > pivot }) end sort([1, 5, 6, 2, 4, 3]) # => [1, 2, 3, 4, 5, 6]
  • 52. Getters & Setters class Robot def name @name end def name=(n) @name = n end def model @model end def model=(m) @model = m end #... end robot = Robot.new robot.name = "HAL" puts robot.name
  • 53. Getters & Setters class Robot attr_accessor :name attr_accessor :model attr_accessor :color attr_accessor :size #... end robot = Robot.new robot.name = "HAL" puts robot.name
  • 54. Getters & Setters   class Accessor def self.create_accessor(accessor_name) define_method(accessor_name) do instance_variable_get("@#{accessor_name}") end define_method("#{accessor_name}=") do |value| instance_variable_set("@#{accessor_name}", value) end end end class Robot < Accessor create_accessor :name create_accessor :model end robot = Robot.new robot.name = "HAL" puts robot.name
  • 55. Getters & Setters   class Object def self.create_accessor(accessor_name) define_method(accessor_name) do instance_variable_get("@#{accessor_name}") end define_method("#{accessor_name}=") do |value| instance_variable_set("@#{accessor_name}", value) end end end class Robot < Accessor create_accessor :name create_accessor :model end robot = Robot.new robot.name = "HAL" puts robot.name
  • 56. Getters & Setters   class Object def self.create_accessor(accessor_name) define_method(accessor_name) do instance_variable_get("@#{accessor_name}") end define_method("#{accessor_name}=") do |value| instance_variable_set("@#{accessor_name}", value) end end end class Robot < Accessor create_accessor :name create_accessor :model end robot = Robot.new robot.name = "HAL" puts robot.name
  • 57. Criando Métodos em Tempo de Execução class Robot def hello(name) puts "Hello #{name}" end end robot = Robot.new robot.hello("IME") # Hello IME
  • 58. class Robot def hello(name) puts "Hello #{name}" end end robot = Robot.new robot.hello_ime # => undefined  method  `hello_ime'  for  #<Robot:0x007ff3e9860c38>  (NoMethodError) Criando Métodos em Tempo de Execução
  • 59. class Robot def hello(name) puts "Hello #{name}" end def method_missing(method_name) name = method_name.to_s.gsub("hello_", "") hello(name.upcase) end end robot = Robot.new robot.hello_ime # => Hello IME robot.hello_igor # => Hello IGOR Criando Métodos em Tempo de Execução
  • 60. Active Record   class Group < ActiveRecord::Base # ... end class Posts < ActiveRecord::Base # ... end class User < ActiveRecord::Base has_many :posts belongs_to :group end user = User.find_by(name: 'Ígor Bonadio') user.posts # => [...] user.group.name # => IME
  • 61. RSpec   RSpec.describe User, :type => :model do it "orders by last name" do lindeman = User.create!(first_name: "Andy", last_name: "Lindeman") chelimsky = User.create!(first_name: "David”, last_name: "Chelimsky") expect(User.ordered_by_last_name).to eq([chelimsky, lindeman]) end end