O que mudou no Ruby 1.9

Click here to load reader

  • date post

    24-May-2015
  • Category

    Technology

  • view

    1.797
  • download

    10

Embed Size (px)

description

Palestra apresentada no Rails Summit 2009

Transcript of O que mudou no Ruby 1.9

  • 1. o que mudouno ruby 1.9nando vieira

2. minhas urls http://simplesideias.com.br http://howtocode.com.br http://spesa.com.br http://twitter.com/fnando http://github.com/fnando 3. ruby 1.9 lanado em dezembro de 2008 prvia estvel da verso 2.0 mais rpido menos memria muitas mudanas 4. YARV BasicObject*splat Oniguruma Fiber RakeThreads m17nDate BlocksLambda ArrayString JSON RubyGems Rdoc ObjectHashSymbol Enumerable 5. m17n multilingualization apenas um tipo de string codicao mutvel pode ser denida de vrias maneiras se estende por toda a linguagem 6. m17n codificaes disponveis ASCII-8BIT IBM437ISO-8859-10 macCroatian UTF-32BE Big5 IBM737ISO-8859-11 macCyrillic UTF-32LE CP51932IBM775ISO-8859-13 macGreekUTF-7 CP850IBM852ISO-8859-14 macIcelandUTF-8 CP852IBM855ISO-8859-15 MacJapanese UTF8-MAC CP855IBM857ISO-8859-16 macRomanWindows-1250 CP949IBM860ISO-8859-2macRomaniaWindows-1251 Emacs-Mule IBM861ISO-8859-3macThai Windows-1252 EUC-JP IBM862ISO-8859-4macTurkishWindows-1253 EUC-KR IBM863ISO-8859-5macUkraineWindows-1254 EUC-TW IBM864ISO-8859-6Shift_JIS Windows-1255 eucJP-ms IBM865ISO-8859-7stateless-Windows-1256 GB12345IBM866ISO-8859-8ISO-2022-JP Windows-1257 GB18030IBM869ISO-8859-9TIS-620 Windows-1258 GB1988 ISO-2022-JP KOI8-RUS-ASCIIWindows-31J GB2312 ISO-2022-JP-2 KOI8-UUTF-16BEWindows-874 GBKISO-8859-1macCentEuro UTF-16LE 7. $KCODE (irb):1: warning: variable $KCODEis no longer effective; ignored 8. m17n em todos os lugaresEm stringstext.encode("utf-8") text.force_encoding("iso-8859-1") Em arquivos# encoding: utf-8 = 2.68ma = "apple" 9. m17n em arquivos # coding: utf-8 # encoding: utf-8 # -*- coding: utf-8 -*- Magic # vim:leencoding=utf-8 Comments /coding[:=] ?/ # vim:set leencoding=utf-8 : 10. m17n em todos os lugaresEm IOf = File.open("file.txt", "r:utf-8")f.external_encoding #=> utf-8 f = File.open("file.txt", "w+:utf-8:iso-8859-1")f.external_encoding #=> utf-8f.internal_encoding #=> iso-8859-1f = File.open("img.png", "r:binary")f.encoding #=> ASCII-8BIT 11. strings codificao "ma".length 1.8 #=> 6"abcd"[0] #=> 97 "ma".length 1.9 #=> 4"abcd"[0] #=> a"abcd".codepoints.to_a[0] Retorna a representao #=> 97numrica dos caracteres "abcd"[0].ord #=> 97 12. strings codificao "u"[0,1] 1.8 #=> 303"".tr("", "aeiou") #=> ueuouuuuuu ""[0] 1.9 #=> "".tr("", "aeiou") #=> aeiou 13. strings enumerable String.ancestors 1.8 #=> [String, Enumerable, Comparable, Object, Kernel]text.each {|line| puts line }String.ancestors 1.9 #=> [String, Comparable, Object, Kernel, BasicObject]text.each_line {|line| puts line } text.each_char {|char| puts char } text.each_byte {|byte| puts byte } text.each_codepoint {|codepoint| puts codepoint } 14. smbolos string-wannabe pode ser comparado com regexes pode ser acessado como strings possui muitos mtodos da classe String :symbol.to_s menos frequente 15. smbolos string-wannabe 1.9 :cool[0] #=> "c":cool =~ /cool/ #=> 0:cool.upcase #=> COOL:"ma".length #=> 4[:c, :b, :a].sort #=> [:a, :b, :c] 16. smbolos blocos to_proc agora nativo muito rpido chars = %w(a b c d) 1_000_000.times { chars.collect(&:upcase) } user system totalreal 1.816.380000 3.700000 20.080000 20.333704user system totalreal 1.9 5.300000 0.0400005.3400005.365868 17. smbolos mtodos & variveis1.8 Object.methods.grep(/variables/) #=> ["class_variables", "instance_variables"]object.instance_variables #=> ["@name", "@type"]Object.methods.grep(/variables/) 1.9 #=> [:class_variables, :instance_variables]object.instance_variables #=> [:name, :type] 18. regexp nova engine utiliza a biblioteca oniguruma muito mais rpida suporta diversas codicaes possui uma sintaxe estendida 19. regexp sintaxe1.9 named groups date = "2009-09-01" regexp = /(?d{4})-(?d{2})-(?d{2})/ date.gsub(regexp, 'k/k/k') #=> 01/09/2009 matches = s.match(/(?d{4})-(?d{2})-(?d{2})/) matches[:year] look behind str = "rasa asa casa" str.gsub(/((? r[asa] asa c[asa]str.gsub(/((? rasa [asa] casa 20. regexp codificao text = "text: " 1.9 match = text.match(/(?b[p{Greek} ]+b)/) match[:greek] #=> Documentao http://www.geocities.jp/kosako3/oniguruma/doc/RE.txtOficial 21. regexp erro comumrequire "open-uri" 1.8contents = open("http://google.com").read_, title = *contents.match(/(.*?)/sim)p title#=> "Google"Encoding::CompatibilityError: incompatible encoding Ruby 1.9:regexp match (Windows-31J regexp with ISO-8859-1 string)/(.*?)/sim/(.*?)/im 22. hash nova sintaxe dict = { 1.8 :mac => "Mac OS X", :win => "Windows Vista Tabajara Version" }redirect_to :action => "show"dict = { 1.9 mac: "Mac OS X", win: "Windows Vista Tabajara Version" }redirect_to action: "show" 23. :key => value 24. hash ordem dos itens hash = {:c => 3, :b => 2, :a => 1} 1.8 #=> {:a=>1, :b=>2, :c=>3}hash.keys #=> [:a, :b, :c] hash = {:c => 3, :b => 2, :a => 1} 1.9 #=> {:c=>3, :b=>2, :a=>1}hash.keys #=> [:c, :b, :a] 25. hash seleo hash.select {|key, value| key == :a } 1.8 #=> [[:a, 1]]hash.index(1) #=> :a Deprecatedhash.select {|key, value| key == :a } 1.9 #=> {:a => 1}hash.key(1) #=> :a Novo mtodo 26. date/time mudanas Time.now.monday?sunday?, monday?, tuesday?, wednesday?, 1.9 #=> truethursday?, friday?, saturday? Time.parse "10/13/2009" 1.8 #=> 2009-10-13mm/dd/aaaavs Time.parse "13/10/2009" 1.9 #=> 2009-10-13dd/mm/aaaa 27. lambda funes annimassum = lambda {|*args| args.reduce(:+) } 1.8sum = lambda {|*args| args.inject(0) {|s,n| s += n; s } }1.9sum = -> *args { args.reduce(:+) }sum.call(1,2,3) #=> 6sum[1,2,3] #=> 6sum.(1,2,3) Ruby 1.9 #=> 6 28. basic object comeando do zero BasicObject.superclass #=> nil Object.superclass #=> BasicObject BasicObject.instance_methods #=> [:==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__] class MyClass < BasicObject; end 29. object #tapuser = User.new.tap do |u| 1.9u.name = "Nando Vieira"u.blog = "http://simplesideias.com.br"end 30. bloco escopo de variveis n = 0 1.8 (1..10).each do |n| end#=> n = 10 n = 0 n = 1 1.9 (1..10).each do |n| lambda {|;n| n = 2 }.call end #=> n = 1 #=> n = 0 31. suporte como lidar com ambas as versesclass Sample if String.method_defined?(:encode) def some_method end else def some_method end end end 32. suporte como lidar com ambas as verses unless String.method_defined?(:encode) class String def encode(*options) end end end 33. mais mudanas operador *splat def group(a, b, *c) 1.8 [a, b, c] endgroup(1,2,3,4,5) #=> [1, 2, [3, 4, 5]]def group(a, *b, c) 1.9 [a, b, c] endgroup(1,2,3,4,5) #=> [1, [2, 3, 4], 5] 34. mais mudanas valor padro de argumentos def color(type, value) 1.8 endComo fazer "type" ser "hex" por padro? color(:rgb, [255, 255, 255]) a) Precisa mudar a ordem dos parmetros color([255, 255, 255]) b) Sempre especificar os 2 parmetros (?)def color(type=:hex, value) 1.9 endcolor(:rgb, [255, 255, 255]) color("#fff") 35. mais mudanas standard library + bundles rubygems, rake, rdoc ber, enumerator, json (ext + pure), minitest,ripper, securerandom, probeproler csv foi substituda por fastcsv soap e wsdl foram removidas 36. mas e a? migrar ou no migrar para o Ruby 1.9? todas as gems foram portadas uma parte do sistema pode ser portada isitruby19.com 37. mas e a? migrar ou no migrar para o Ruby 1.9? testes pelo menos as partes crticas 38. one more thingapenas R$10http://howtocode.com.br 39. dvidas? 40. obrigado [email protected]