Ruby - Uma Introdução
-
Upload
igor-bonadio -
Category
Software
-
view
147 -
download
2
Transcript of Ruby - Uma Introdução
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 endend
Inspirações: Perl
class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off endend
Inspirações: Perl
class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off endend
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 + nend# => 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:~$ irb2.2.0 :001 >
IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1
IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 >
IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next
IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 >
IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u
IRB igorbonadio@marvin:~$ irb2.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".upcase2.2.0 :003 > "blah".u
IRB igorbonadio@marvin:~$ irb2.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:~$ irb2.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:~$ irb2.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.rbHello 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 comando2else outro_comando1 outro_comando2 outro_comando3end
Laços
while x < 3 comando1 comando2end
for x in [1, 2, 3] puts xend
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 + bend
sum(1, 2) # => 3
sum 4, 5 # => 9
Closures
def map(vector, &function) resp = [] vector.each do |elem| resp << function.call(elem) end respend
map([1,2,3]) do |x| 2*xend# => [2, 4, 6]
Closures
def map(vector, &function) resp = [] vector.each do |elem| resp << function.call(elem) end respend
map [1,2,3] do |x| 2*xend# => [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") endend
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") endend
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") endend
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") endend
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") endend
Duck Typing class Robot def walk_to(x, y) #... end
def bip() #... endend
class Person def walk_to(x, y) #... end def talk(msg) #... endend
def go_to(obj, x, y) obj.walk_to(x, y)end
def bip(obj) obj.bip()end
go_to(Robot.new, 1, 2) # okgo_to(Person.new, 1, 2) # ok
bip(Robot.new) # okbip(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.newrobot.name = "HAL"puts robot.name
Getters & Setters
class Robot attr_accessor :name attr_accessor :model attr_accessor :color attr_accessor :size #...end
robot = Robot.newrobot.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 endend
class Robot < Accessor create_accessor :name create_accessor :modelend
robot = Robot.newrobot.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 endend
class Robot < Accessor create_accessor :name create_accessor :modelend
robot = Robot.newrobot.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 endend
class Robot < Accessor create_accessor :name create_accessor :modelend
robot = Robot.newrobot.name = "HAL"puts robot.name
Criando Métodos em Tempo de Execução
class Robot def hello(name) puts "Hello #{name}" endend
robot = Robot.newrobot.hello("IME")
# Hello IME
class Robot def hello(name) puts "Hello #{name}" endend
robot = Robot.newrobot.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) endend
robot = Robot.newrobot.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 :groupend
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]) endend
Links Úteis
http://www.rubygems.org
https://www.ruby-toolbox.com