Aula 3. 09/03/2015. Práticas de Desenvolvimento de Software Aula 3 - Introdução à linguagem de programação Ruby Oferecimento
Ruby (1) Ruby
Ruby (2) Ruby Linguagem de programação dinâmica, de código aberto, com foco em simplicidade e produtividade. Tem sintaxe elegante, natural para ler e fácil de escrever.
Ruby (3) Ruby Matz 2005 Multi Open source Yukihiro Matsumoto criou a linguagem em 1995. I was thinking about the possibility of an objectoriented scripting language. Perl was ugly. Python wasn t a true OO language.
Ruby (4) Ruby Matz 2005 Multi Open source Em 2005, Ruby ganhou popularidade junto com o framework de desenvolvimento web Ruby on Rails.
Ruby (5) Ruby Matz 2005 Multi Open source É uma linguagem multiparadigma (procedural, OO, funcional), multiplataforma (Linux, Mac, Windows) e tipicamente interpretada (Matz's Ruby Interpreter).
Ruby (6) Ruby Matz 2005 Multi Open source https://github.com/ruby/ruby
Ruby (7) Aplicações criadas com Ruby
Linguagem compilada vs. interpretada (1) Linguagem compilada vs. interpretada
Linguagem compilada vs. interpretada (2) Processo em uma linguagem compilada Desenvolvedor Usuário "compilar" "executar" Código fonte Código executável A compilação gera um arquivo binário nativo com instruções de máquina Executa nativamente
Linguagem compilada vs. interpretada (3) Processo em uma linguagem interpretada Desenvolvedor "executar" Código fonte Trecho executável Trechos de código são compilados dinamicamente por um interpretador Executa trecho
Linguagem compilada vs. interpretada (3) Processo em uma linguagem interpretada Desenvolvedor Usuário "executar" Código fonte Trecho executável Trechos de código são compilados dinamicamente por um interpretador Executa trecho
Linguagem compilada vs. interpretada (4) Java é uma linguagem compilada?
Linguagem compilada vs. interpretada (5) Processo em Java Desenvolvedor Usuário "compilar" "executar" Código fonte Código executável pela JVM A compilação gera um arquivo bytecode com instruções para a máquina virtual java (JVM) Interpreta com a JVM
Linguagem compilada vs. interpretada (6) E o que Ruby tem com isso?
Linguagem compilada vs. interpretada (7) Ruby Pode ser interpretada ou compilada. MRI mruby jruby ironruby RubyMotion Rubinius Matz Ruby Interpreter (interpretador mais popular de Ruby) Implementação leve/"embeddable" de Ruby Implementação em Java Implementação em.net Implementação comercial que roda em ios, OS X e Android Implementação em Ruby capaz de compilar Ruby
Instalação de um interpretador Ruby RVM é uma ferramenta em linha de comando que permite instalar, gerenciar e trabalhar com múltiplos ambientes (interpretadores/bibliotecas) de Ruby facilmente. https://rvm.io/
Scripts em Ruby (1) DEMO irb (Interactive Ruby) Permite interpretar código passo a passo
Scripts em Ruby (1) DEMO Execução de um script
Estrutura da linguagem de programação Ruby (1) Tipos de dados mais comuns Tipo Nulo Booleano Exemplos nil true, false Inteiro 1, 100, 3000, 3_000 Ponto flutuante String Símbolos 2.53, 3.1415, 3000.2, 3_000.20 "duplas", 'simples' :username, :password, :name, :age Array [1, 2, 3] Hash { 'a' => 1, 'b' => 2, 3 => 'c' }
Estrutura da linguagem de programação Ruby (2) Operadores aritméticos Operador Exemplos + 1 + 1 # 2-9 - 5 # 4 * 3 * 2 # 6 / 10 / 3 # 3 % 10 % 3 # 1
Estrutura da linguagem de programação Ruby (3) Operadores relacionais Operador Exemplos > 5 > 5 # false >= 5 >= 5 # true < 3 < 4 # true <= 3 <= 2.9 # false == 5 == 5.5 # false!= 5!= 5.5 # true
Estrutura da linguagem de programação Ruby (4) Operadores condicionais Operador && and Exemplos true && false # false true and false # false true false # true or true or false # true!!true # false not not true # false
Estrutura da linguagem de programação Ruby (5) Operadores de atribuição Operador Exemplos = num = 1 # 1 += -= *= /= %= num = 1 num += 1 # 2 num = 1 num -= 1 # 0 num = 2 num *= 3 # 6 num = 4 num /= 2 # 2 num = 3 num %= 2 # 1
Sintaxe da linguagem de programação Ruby (1) Comentário # This is an inline comment =begin # This is a multiline comment def todo end =end def done puts "Ready to go" end
Sintaxe da linguagem de programação Ruby (1) String # String concatenation. a = "Hello" b = "World" c = a + b # => "HelloWorld" # String interpolation. s = "2 * 3 = #{2*3}" # => "2 * 3 = 6"
Sintaxe da linguagem de programação Ruby (1) Array # Create a new array with numbers. a = [ 1, 2, 3, 4, 5 ] a[0] # 1 a[4] # 5 a[-1] # 5 a.pop # remove the last element (5) a.shift # remove the first element (1) a.push(10) # add 10 to the tail of the array a.unshift(20) # add 20 to the head of the array a.size a.index(2) # length/size of the array # position of the 1st occurrence # of element 2 in the array a.count(3) # how many times the element 3 # occurs in the array
Sintaxe da linguagem de programação Ruby (1) Hash # A Ruby Hash is an associative table. h = { :name => 'Rafael', :surname => 'Barbolo', :age => 27 } h[:name] # "Rafael" h[:surname] # "Barbolo" h[:age] # 27 a.size # 3, how many associations (keys/values) a.keys # [ :name, :surname, :age ] a.values # [ "Rafael", "Barbolo", 27 ]
Sintaxe da linguagem de programação Ruby (1) Funções (1) # It's a Ruby convention to use snake_case instead # of CamelCase for functions and variables names. def function_name(arg1, arg2 = 3) puts "This function receives arg1 and arg2." puts "The default value of arg2 is 3." puts "The result is the product of arg1 with arg2." return arg1 * arg2 # "return" can be omitted end function_name(2) # 6 function_name(2, 4) # 8
Sintaxe da linguagem de programação Ruby (1) Funções (2) def function_name puts "This function doesn't receive arguments." puts "The result will always be 1000." 1000 end function_name() # 1000 function_name # 1000
Sintaxe da linguagem de programação Ruby (1) Impressão # Examples of printing functions print "printing without line break" puts "printing with line break" p "p is an alias of puts" puts 2*5 # => 10
Sintaxe da linguagem de programação Ruby (1) Controle condicional: if/else # Example of conditional control with if/else if condition1 puts "condition 1 is met" elsif condition2 puts "condition 2 is met" else puts "no conditions met" end
Sintaxe da linguagem de programação Ruby (1) Controle condicional: case/when # Example of conditional control with case/when case condition when 1 puts "condition 1 is met" when 2 puts "condition 2 is met" else puts "no conditions met" end
Sintaxe da linguagem de programação Ruby (1) Controle de iteração: while # Example of loop control with while while some_condition next # jump to the next iteration redo # reexecute the current iteration break # break the loop end
Sintaxe da linguagem de programação Ruby (1) Controle de iteração: each # There is "for" in Ruby, however it's rarely used. # The convention is to use object's methods to navigate # throughout the elements. # Example on how to navigate in an Array's elements array = [ 1, 2, 3, 4, 5 ] array.each do element puts element*10 end
Sintaxe da linguagem de programação Ruby (1) Leitura/escrita em arquivo # Read from file contents = File.open("path/to/file", "r").read # Write to file contents = "this is the content to be written" f = File.open("path/to/file", "w") f.write(contents) f.close
Instalação de bibliotecas e dependências (1) RubyGems RubyGems é o serviço de hospedagem de gems (bibliotecas) da comunidade Ruby. https://rubygems.org/
Instalação de bibliotecas e dependências (2) DEMO RubyGems gem install rails (exemplo de como instalar a gem Rails) https://rubygems.org/
Exemplo de um programa que calcula o fibonacci de um número DEMO fibonacci.rb # fibonacci: 1 1 2 3 5 8 13 def fibonacci(n) return n if [0, 1].include? n fibonacci(n - 1) + fibonacci(n - 2) end # Example on how to use: # fibonacci(6) # 8
Bibliografia: referência para esta aula Programming Ruby Dave Thomas Primeira edição gratuita: http://ruby-doc.com/docs/programmingruby/