64
Ruby Uma introdução ÍGOR BONADIO

Ruby - Uma Introdução

Embed Size (px)

Citation preview

Page 1: Ruby - Uma Introdução

Ruby Uma introdução

ÍGOR BONADIO

Page 2: Ruby - Uma Introdução

Origem

Page 3: Ruby - Uma Introdução

Criador •  Yukihiro Matsumoto (Matz) •  Japão, 1995

Page 4: Ruby - Uma Introdução

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  

Page 5: Ruby - Uma Introdução

Inspirações: Perl

class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off endend

Page 6: Ruby - Uma Introdução

Inspirações: Perl

class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off endend

Page 7: Ruby - Uma Introdução

Inspirações: Perl

class Robot def walk_to(x, y) @engine.turn_on @engine.go_to(x, y, $map) @engine.turn_off endend

Page 8: Ruby - Uma Introdução

Inspirações: Smalltalk

1.next # => 2

Robot.methods # => [:walk_to, ...]

Page 9: Ruby - Uma Introdução

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  

Page 10: Ruby - Uma Introdução

Inspirações: Lisp

[1, 2, 3].map {|n| n*2}# => [2, 4, 6]

[1, 2, 3].reduce do |acc, n| acc + nend# => 6

Page 11: Ruby - Uma Introdução

Ruby •  Script •  Interpretada •  Tipagem forte e dinâmica – Duck Typing

•  Orientada a objetos •  Com características funcionais

Page 12: Ruby - Uma Introdução

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)

Page 13: Ruby - Uma Introdução

Configurando e Conhecendo o Ambiente

Page 14: Ruby - Uma Introdução

RVM •  Gerencia diversas versões – MRI (1.9.3, 2.2.3, etc) – JRuby – Rubinious – MacRuby – MagLev

Page 15: Ruby - Uma Introdução

RVM

$ \curl -sSL https://get.rvm.io | bash -s stable

Page 16: Ruby - Uma Introdução

RVM

$ \curl -sSL https://get.rvm.io | bash -s stable

$ rvm install 2.2.3

Page 17: Ruby - Uma Introdução

RVM

$ \curl -sSL https://get.rvm.io | bash -s stable

$ rvm install 2.2.3

$ rvm use 2.2.3

Page 18: Ruby - Uma Introdução

Note que... •  Ruby funciona muito bem em – Linux – OSX – BSD

•  Mas não muito bem em Windows...

Page 19: Ruby - Uma Introdução

IRB igorbonadio@marvin:~$ irb2.2.0 :001 >

Page 20: Ruby - Uma Introdução

IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1

Page 21: Ruby - Uma Introdução

IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 >

Page 22: Ruby - Uma Introdução

IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next

Page 23: Ruby - Uma Introdução

IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 >

Page 24: Ruby - Uma Introdução

IRB igorbonadio@marvin:~$ irb2.2.0 :001 > 1 + 1 => 2 2.2.0 :002 > 2.next => 3 2.2.0 :003 > "blah".u

Page 25: Ruby - Uma Introdução

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

Page 26: Ruby - Uma Introdução

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

Page 27: Ruby - Uma Introdução

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 >

Page 28: Ruby - Uma Introdução

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

Page 29: Ruby - Uma Introdução

Interpretador

$ ruby -e "puts 'Hello IME'"Hello IME

Page 30: Ruby - Uma Introdução

Interpretador  

$ ruby -e "puts 'Hello IME'"Hello IME

hello.rb  

puts  ‘Hello  IME’  

Page 31: Ruby - Uma Introdução

Interpretador  

$ ruby -e "puts 'Hello IME'"Hello IME$ ruby hello.rbHello IME

hello.rb  

puts  ‘Hello  IME’  

Page 32: Ruby - Uma Introdução

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)

...

Page 33: Ruby - Uma Introdução

A Linguagem

Page 34: Ruby - Uma Introdução

Declaração de Variáveis

name = "Ígor Bonadio"

NUMBER = 123

$os = "OSX"

Page 35: Ruby - Uma Introdução

Tudo é Objeto!

1.next # => 2

"blah".upcase # => "BLAH"

[1, 2, 3].size # => 3

Page 36: Ruby - Uma Introdução

Condicionais

if x < 3 comando1 comando2else outro_comando1 outro_comando2 outro_comando3end

Page 37: Ruby - Uma Introdução

Laços

while x < 3 comando1 comando2end

for x in [1, 2, 3] puts xend

Page 38: Ruby - Uma Introdução

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!

Page 39: Ruby - Uma Introdução

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!

Page 40: Ruby - Uma Introdução

Funções

def sum(a, b) a + bend

sum(1, 2) # => 3

sum 4, 5 # => 9

Page 41: Ruby - Uma Introdução

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]

Page 42: Ruby - Uma Introdução

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]

Page 43: Ruby - Uma Introdução

Strings vs Symbols

color_str = "Orange"color_sym = :Orange

if color_str == "Blue" # ...end

if color_sym == :Blue # ...end

Page 44: Ruby - Uma Introdução

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

Page 45: Ruby - Uma Introdução

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

Page 46: Ruby - Uma Introdução

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

Page 47: Ruby - Uma Introdução

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

Page 48: Ruby - Uma Introdução

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

Page 49: Ruby - Uma Introdução

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

Page 50: Ruby - Uma Introdução

Exemplos

Page 51: Ruby - Uma Introdução

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]

Page 52: Ruby - Uma Introdução

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

Page 53: Ruby - Uma Introdução

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

Page 54: Ruby - Uma Introdução

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

Page 55: Ruby - Uma Introdução

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

Page 56: Ruby - Uma Introdução

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

Page 57: Ruby - Uma Introdução

Criando Métodos em Tempo de Execução

class Robot def hello(name) puts "Hello #{name}" endend

robot = Robot.newrobot.hello("IME")

# Hello IME

Page 58: Ruby - Uma Introdução

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

Page 59: Ruby - Uma Introduçã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

Page 60: Ruby - Uma Introduçã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

Page 61: Ruby - Uma Introdução

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

Page 62: Ruby - Uma Introdução

Links Úteis

Page 63: Ruby - Uma Introdução

http://www.rubygems.org

Page 64: Ruby - Uma Introdução

https://www.ruby-toolbox.com