SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Getfilestruct zbksh(1)
Getfilestruct zbksh(1)
Ben Pope
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails Workshop
Andre Foeken
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with Moose
Dave Cross
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
chrismdp
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介
Wen-Tien Chang
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
Lin Yo-An
 

Was ist angesagt? (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
 

Andere mochten auch

1st response Final presentation
1st response Final presentation1st response Final presentation
1st response Final presentation
floodprojects
 
Bimba kids teen - 25-08-2013
Bimba kids teen - 25-08-2013Bimba kids teen - 25-08-2013
Bimba kids teen - 25-08-2013
Regina Lissone
 
Tawanda glover presentation
Tawanda glover presentationTawanda glover presentation
Tawanda glover presentation
ttglover
 
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
Nitram Seyer
 

Andere mochten auch (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
 

Ähnlich wie Ruby - Uma Introdução

Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
Wen-Tien Chang
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02
Apoorvi Kapoor
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
ppparthpatel123
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 

Ähnlich wie 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
 

Kürzlich hochgeladen

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Kürzlich hochgeladen (20)

WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 

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