1 / 46

Ruby

Ruby. André Braga Patrícia Lustosa. Yukihiro Matsumoto ( “ Matz ” ), 1993. “Natural, not simple” “More powerful than Perl and more OO than Python”. Perl Smalltalk Eiffel Ada Lisp. Simplicidade e Produtividade. Para pessoas Sintaxe elegante e fácil

isanne
Télécharger la présentation

Ruby

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ruby André Braga PatríciaLustosa

  2. Yukihiro Matsumoto (“Matz”), 1993 “Natural, not simple” “More powerful than Perl and more OO than Python” Perl Smalltalk Eiffel Ada Lisp

  3. Simplicidade e Produtividade • Para pessoas • Sintaxeelegante e fácil • Fácil de ler e escrever • Poderosa • Interpretada • Tipagemdinâmica • OO : TUDO é objeto • Semtiposprimitivos.

  4. Convenções • Classes e Módulos • Métodos • Variáveislocais • Variáveis de instância MinhaClasse meu_metodo_legal minha_variavel @var_de_instancia

  5. Programando • IRB (Interactive Ruby) • SciTE (editor) • F5 paraexecutar

  6. Tudo é objeto 1)

  7. Orientação a Objetos • Como em Smalltalk, tudo é objeto • C++ e Java: híbridas • Objetos e tiposprimitivos Maiseficienteparaalgumasaplicações, mas… OO puro é maisconsistente e fácil de usar

  8. Orientação a Objetos • Tiposprimitivos: -1.abs • Nil: nil.methods • Classes: Song.new • Blocos: podematé ser passadoscomoparâmetros

  9. Variáveis 2)

  10. Variáveis • Podem ser • locais • globais • de instância • ou estáticas • E podem ser constantes localVar = 2 $globalVar = “3” @instaceVar = 4.3 @@staticVar = [2,3] Pi = 3.1416 Name = “Ruby”

  11. Escopo

  12. Constantes

  13. Tipos 3)

  14. String Number Symbol Array Hash String • Aspas simples ouduplas Permiteminterpolação #{expressão}: def metodo_qualquer(nome) puts “O nome é: #{nome}” end

  15. String Number Symbol Array Hash String Caracteres de escape \” \\ \abell/alert \bbackspace \rcarriage return \n \s \t

  16. String Number Symbol Array Hash String Algunsmétodos concat, <<, + <=>, ==, eql? include? length, size to_f, to_ifloat/int to_sde outrostipos

  17. String Number Symbol Array Hash String >> puts “hello,\nworld” hello, World >>%w(a b c) (separanosespaçosembranco) => [“a”, “b”, “c”]

  18. StringNumber Symbol Array Hash Number • Fixnum • Inteiros entre -230 and 230-1 • Bignum • Fora do intervalo de Fixnum, “infinitos”. Limiteaproximado: 2218 • Float • Conversãoautomática

  19. StringNumber Symbol Array Hash • Como tudo é objeto… operadoressãoaçucaressintáticos! 4 + 7  4.+(7) >> var_a = 300 >> var_a.class >> var_a += 40832000000 >> var_a.class => 300 => Fixnum => 40832000300 => Bignum

  20. StringNumber Symbol Array Hash Symbol • Representaçãointerna de um nome • Atômico, imutável e único • Todas as referênciaspara um únicoobjeto >> :my_value.equal?(:my_value) => true >> “my_value”.equal?(“my_value”) => false

  21. StringNumber Symbol Array Hash • Economia de memória! • Fáceis de usar, ficamais bonito… • Uso: • Hash keys (:name=> ‘Brian’, :hobby=> ‘golf’) • Parâmetros (:name, :title) • Nomes de métodos (:post_comment)

  22. StringNumber Symbol Array Hash Array Hash • Arrays • [“a”, “b”, 3, 5.6] • Hash • Chaves apotandoparavalores • Cadachave é única • Hash.newoumeu_hash={“a” => 1, “b”=>2}

  23. PalavrasReservadas 4)

  24. Reserved Keywords =begin =end alias and begin BEGIN break case class def defined? do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless untilwhenwhileyield

  25. Estruturas de Controle 5)

  26. Condicionais

  27. Condicionais

  28. Loop

  29. Loop

  30. Loop

  31. Classes 6)

  32. Definindo Classes

  33. Instanciação • Uma instância é criada a partir de uma classe usando o método new (de Class) anObject = MyClass.new(parameters) • Essa função constrói um objeto na memória e passa a execução para a função initialize da classe, se houver.

  34. Exemplo

  35. Variáveis de Instância >ruby rocketShip.rb rocketShip.rb:13: undefined method `destination' for #<RocketShip:0x27f5510 @destination="Netptune"> (NoMethodError) >Exit code: 1

  36. Writers and Readers

  37. Accessors

  38. Herança • Suporte à herança simples • Todos os atributos e métodos não-privados de super-classe são herdados pela sub-classe.

  39. Herança

  40. Módulos • Módulos são coleções de métodos • Classes podem ´mixin´ um módulo e receber todos os métodos do módulo diretamente • Simulam herança múltipla

  41. Comparable < Módulo > <= Classe < = > >= == between

  42. Comparable pessoa.rb:19: undefined method `<' for #<Pessoa:0x27f4688 @nome="Paty", @idade=21> (NoMethodError)

  43. Incluindo Comparable

  44. ExpressõesRegulares 7)

  45. /regex/ • Casamento de padrões

  46. /(c|C)omp\w+.*s/ retorna a posição retorna o quecasou

More Related