Download - O que mudou no Ruby 1.9

Transcript
Page 1: O que mudou no Ruby 1.9

o que mudou

nando vieira

no ruby 1.9

Page 2: O que mudou no Ruby 1.9

minhas urls• http://simplesideias.com.br

• http://howtocode.com.br

• http://spesa.com.br

• http://twitter.com/fnando

• http://github.com/fnando

• http://simplesideias.com.br

• http://howtocode.com.br

• http://spesa.com.br

• http://twitter.com/fnando

• http://github.com/fnando

Page 3: O que mudou no Ruby 1.9

ruby 1.9• lançado em dezembro de 2008

• prévia estável da versão 2.0

• mais rápido

• menos memória

• muitas mudanças

Page 4: O que mudou no Ruby 1.9

YARV

JSON

m17n

BasicObjectOniguruma

DateFiber

Hash Enumerable

LambdaBlocks

RubyGems

Rake

Rdoc

*splat

ObjectString

Array

Threads

Symbol

Page 5: O que mudou no Ruby 1.9

m17nmultilingualization

• apenas um tipo de string

• codificação é mutável

• pode ser definida de várias maneiras

• se estende por toda a linguagem

Page 6: O que mudou no Ruby 1.9

m17nASCII-8BITBig5CP51932CP850CP852CP855CP949Emacs-MuleEUC-JPEUC-KREUC-TWeucJP-msGB12345GB18030GB1988GB2312GBK

IBM437IBM737IBM775IBM852IBM855IBM857IBM860IBM861IBM862IBM863IBM864IBM865IBM866IBM869ISO-2022-JPISO-2022-JP-2ISO-8859-1

ISO-8859-10ISO-8859-11ISO-8859-13ISO-8859-14ISO-8859-15ISO-8859-16ISO-8859-2ISO-8859-3ISO-8859-4ISO-8859-5ISO-8859-6ISO-8859-7ISO-8859-8ISO-8859-9KOI8-RKOI8-UmacCentEuro

macCroatianmacCyrillicmacGreekmacIcelandMacJapanesemacRomanmacRomaniamacThaimacTurkishmacUkraineShift_JISstateless-ISO-2022-JPTIS-620US-ASCIIUTF-16BEUTF-16LE

UTF-32BEUTF-32LEUTF-7UTF-8UTF8-MACWindows-1250Windows-1251Windows-1252Windows-1253Windows-1254Windows-1255Windows-1256Windows-1257Windows-1258Windows-31JWindows-874

codificações disponíveis

Page 7: O que mudou no Ruby 1.9

$KCODE(irb):1: warning: variable $KCODE

is no longer effective; ignored

Page 8: O que mudou no Ruby 1.9

m17n

text.encode("utf-8")

Em strings

Em arquivos

text.force_encoding("iso-8859-1")

# encoding: utf-8£ = 2.68maçã = "apple"

em todos os lugares

Page 9: O que mudou no Ruby 1.9

m17n # coding: utf-8 # encoding: utf-8 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 # vim:set fileencoding=utf-8 :

MagicComments/coding[:=] ?/

em arquivos

Page 10: O que mudou no Ruby 1.9

m17n

f = File.open("file.txt", "r:utf-8")f.external_encoding #=> utf-8

Em IO

f = File.open("file.txt", "w+:utf-8:iso-8859-1")f.external_encoding #=> utf-8f.internal_encoding #=> iso-8859-1

f = File.open("img.png", "r:binary")f.encoding #=> ASCII-8BIT

em todos os lugares

Page 11: O que mudou no Ruby 1.9

stringscodificação

"maçã".length#=> 6

"maçã".length#=> 41.9

1.8"abcd"[0]#=> 97

"abcd"[0]#=> a

"abcd"[0].ord#=> 97

"abcd".codepoints.to_a[0]#=> 97

Retorna a representação numérica dos caracteres

Page 12: O que mudou no Ruby 1.9

stringscodificação

"áéíóu"[0,1]#=> \303

"áéíóú"[0]#=> á1.9

1.8"áéíóú".tr("áéíóú", "aeiou")#=> ueuouuuuuu

"áéíóú".tr("áéíóú", "aeiou")#=> aeiou

Page 13: O que mudou no Ruby 1.9

stringsenumerable

String.ancestors#=> [String, Enumerable, Comparable, Object, Kernel]

String.ancestors#=> [String, Comparable, Object, Kernel, BasicObject]1.9

1.8text.each {|line| puts line }

text.each_line {|line| puts line }text.each_char {|char| puts char }text.each_byte {|byte| puts byte }text.each_codepoint {|codepoint| puts codepoint }

Page 14: O que mudou no Ruby 1.9

símbolosstring-wannabe

• pode ser comparado com regexes

• pode ser acessado como strings

• possui muitos métodos da classe String

• :symbol.to_s é menos frequente

Page 15: O que mudou no Ruby 1.9

símbolosstring-wannabe

:cool[0]#=> "c"1.9:cool =~ /cool/#=> 0

:cool.upcase#=> COOL

:"maçã".length#=> 4

[:c, :b, :a].sort#=> [:a, :b, :c]

Page 16: O que mudou no Ruby 1.9

símbolosblocos

chars = %w(a b c d)1_000_000.times { chars.collect(&:upcase) }

• to_proc agora é nativo

• é muito rápido

1.8

1.9 user system total real 5.300000 0.040000 5.340000 5.365868

user system total real16.380000 3.700000 20.080000 20.333704

Page 17: O que mudou no Ruby 1.9

símbolosmétodos & variáveis

1.8

1.9

Object.methods.grep(/variables/)#=> ["class_variables", "instance_variables"]

Object.methods.grep(/variables/)#=> [:class_variables, :instance_variables]

object.instance_variables#=> ["@name", "@type"]

object.instance_variables#=> [:name, :type]

Page 18: O que mudou no Ruby 1.9

regexpnova engine

• utiliza a biblioteca oniguruma

• muito mais rápida

• suporta diversas codificações

• possui uma sintaxe estendida

Page 19: O que mudou no Ruby 1.9

regexpsintaxe

1.9 named groupsdate = "2009-09-01"regexp = /(?<ano>\d{4})-(?<mes>\d{2})-(?<dia>\d{2})/date.gsub(regexp, '\k<dia>/\k<mes>/\k<ano>')#=> 01/09/2009

look behindstr = "rasa asa casa"str.gsub(/((?<=[rc])asa)/, '[\1]')#=> r[asa] asa c[asa]

str.gsub(/((?<![rc])asa)/, '[\1]')#=> rasa [asa] casa

matches = s.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)matches[:year]

Page 20: O que mudou no Ruby 1.9

regexpcodificação

1.9 text = "text: Γενηθη ́τω φω ͂ς"match = text.match(/(?<greek>\b[\p{Greek} ]+\b)/)match[:greek]#=> Γενηθη ́τω φω ͂ς

http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt OficialDocumentação

Page 21: O que mudou no Ruby 1.9

regexperro comum

1.8 require "open-uri" contents = open("http://google.com").read _, title = *contents.match(/<title>(.*?)<\/title>/sim) p title#=> "Google"

Encoding::CompatibilityError: incompatible encoding regexp match (Windows-31J regexp with ISO-8859-1 string)Ruby 1.9:

/<title>(.*?)<\/title>/sim /<title>(.*?)<\/title>/im

Page 22: O que mudou no Ruby 1.9

hashnova sintaxe

1.8 dict = { :mac => "Mac OS X", :win => "Windows Vista Tabajara Version"}

dict = { mac: "Mac OS X", win: "Windows Vista Tabajara Version"}

1.9

redirect_to :action => "show"

redirect_to action: "show"

Page 23: O que mudou no Ruby 1.9

:key => value

Page 24: O que mudou no Ruby 1.9

hashordem dos itens

1.8 hash = {:c => 3, :b => 2, :a => 1}#=> {:a=>1, :b=>2, :c=>3}

hash = {:c => 3, :b => 2, :a => 1}#=> {:c=>3, :b=>2, :a=>1}1.9

hash.keys#=> [:a, :b, :c]

hash.keys#=> [:c, :b, :a]

Page 25: O que mudou no Ruby 1.9

hashseleção

1.8 hash.select {|key, value| key == :a }#=> [[:a, 1]]

hash.select {|key, value| key == :a }#=> {:a => 1}1.9

hash.index(1)#=> :a

hash.key(1)#=> :a

Deprecated

Novo método

Page 26: O que mudou no Ruby 1.9

date/timemudanças

1.9 Time.now.monday?#=> true

sunday?, monday?, tuesday?, wednesday?, thursday?, friday?, saturday?

1.8 Time.parse "10/13/2009"#=> 2009-10-13

1.9 Time.parse "13/10/2009"#=> 2009-10-13

mm/dd/aaaa

dd/mm/aaaavs

Page 27: O que mudou no Ruby 1.9

lambdafunções anônimas

1.8 sum = lambda {|*args| args.reduce(:+) }

1.9 sum = -> *args { args.reduce(:+) }

sum = lambda {|*args| args.inject(0) {|s,n| s += n; s } }

sum.call(1,2,3)#=> 6

sum[1,2,3]#=> 6

sum.(1,2,3)#=> 6

Ruby 1.9

Page 28: O que mudou no Ruby 1.9

basic objectcomeçando do zero

BasicObject.superclass#=> nil

Object.superclass#=> BasicObject

BasicObject.instance_methods#=> [:==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__]

class MyClass < BasicObject; end

Page 29: O que mudou no Ruby 1.9

object#tap

1.9 user = User.new.tap do |u| u.name = "Nando Vieira" u.blog = "http://simplesideias.com.br"end

Page 30: O que mudou no Ruby 1.9

blocoescopo de variáveis

1.8 n = 0

(1..10).each do |n|end

#=> n = 10

1.9 n = 0

(1..10).each do |n|end

#=> n = 0

n = 1

lambda {|;n| n = 2 }.call

#=> n = 1

Page 31: O que mudou no Ruby 1.9

suportecomo lidar com ambas as versões

class Sample if String.method_defined?(:encode) def some_method end else def some_method end endend

Page 32: O que mudou no Ruby 1.9

suportecomo lidar com ambas as versões

unless String.method_defined?(:encode) class String def encode(*options) end endend

Page 33: O que mudou no Ruby 1.9

mais mudançasoperador *splat

1.8 def group(a, b, *c) [a, b, c]end

group(1,2,3,4,5)#=> [1, 2, [3, 4, 5]]

1.9 def group(a, *b, c) [a, b, c]end

group(1,2,3,4,5)#=> [1, [2, 3, 4], 5]

Page 34: O que mudou no Ruby 1.9

mais mudançasvalor padrão de argumentos

1.8 def color(type, value)end

color(:rgb, [255, 255, 255])color([255, 255, 255])

1.9 def color(type=:hex, value)end

color(:rgb, [255, 255, 255])color("#fff")

a) Precisa mudar a ordem dos parâmetrosb) Sempre especificar os 2 parâmetros (?)

Como fazer "type" ser "hex" por padrão?

Page 35: O que mudou no Ruby 1.9

mais mudançasstandard library + bundles

• rubygems, rake, rdoc

• fiber, enumerator, json (ext + pure), minitest, ripper, securerandom, probeprofiler

• csv foi substituída por fastcsv

• soap e wsdl foram removidas

Page 36: O que mudou no Ruby 1.9

mas e aí?migrar ou não migrar para o Ruby 1.9?

• todas as gems foram portadas

• uma parte do sistema pode ser portada

isitruby19.com

Page 37: O que mudou no Ruby 1.9

mas e aí?migrar ou não migrar para o Ruby 1.9?

testespelo menos as partes críticas

Page 38: O que mudou no Ruby 1.9

one more thing

apenas R$10http://howtocode.com.br

Page 39: O que mudou no Ruby 1.9

dúvidas?