SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
puts “Hello Ruby!”
Clean, Elegant
      and
Meaningful Syntax
test_string = 'string for test'
puts 'matched' if test_string.match 'string'




files = Dir['*.txt']
for file in files
    file_ref = open file
    file_ref.each_line { |line| puts line.reverse.upcase }
end
Everything is an Object


10.times { puts “Hello World!” }   “Hello World!”.methods
Dynamic Typing,
  Duck Typing
     and
 Open Classes
a_variable = 'a b c'.split(' ')   #=> ['a','b','c']
a_variable = a_variable.join(' ') #=> 'a b c'



def a_function object_par
     puts object_par.crazy_method
end

a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array

class Array
    def crazy_method
         return 'crazy method for an array'
    end
end

a_function [1,2,3] #=> puts 'crazy method for an array'
a_variable = 'a b c'.split(' ')   #=> ['a','b','c']
a_variable = a_variable.join(' ') #=> 'a b c'



def a_function object_par
     puts object_par.crazy_method
end

a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array

class Array
    def crazy_method
         return 'crazy method for an array'
    end
end

a_function [1,2,3] #=> puts 'crazy method for an array'
def a_function object_par
     puts object_par.crazy_method
end

some_obj = SomeClass.new

a_function some_obj #=> error: undefined method 'crazy_method' for class SomeClass

def some_obj.crazy_method
     return 'this is a crazy feature'
end

a_function some_obj #=> puts 'this is a crazy_feature'
def a_function object_par
     puts object_par.crazy_method
end

some_obj = SomeClass.new

a_function some_obj #=> error: undefined method 'crazy_method' for class SomeClass

def some_obj.crazy_method
     return 'this is a crazy feature'
end

a_function some_obj #=> puts 'this is a crazy_feature'
"if it walks like a duck and quacks like a
           duck, then it is a duck”
Blocks
def square an_array
    return an_array.map { |e| e*e }
end




lines_of_a_doc.each_with_index do |line,i|
    if i.even? then
          puts 'even line: #{line}'
    else
          puts 'odd line: ' + line
    end
end
[1,2,3,4].select { |e| e.even? }
#=> [2,4]

[1,2,3,4].collect { |e| e.even? }
#=> [true,false,true,false]

[1,2,3,4].inject(0) { |sum,e| sum += e }
#=> 10
def my_for n
   n.times { |n| yield(n) }
end

my_for 3 { |i| puts i }

#=> 1
#=> 2
#=> 3
Mix-in
class Books < Collection
    def initialize
         @books = SomeReader.new('some_file_with_books').get_books
    end

      include Enumerable

      def each
          @books.each { |book| yield(book) }
      end
end




        Class Books now have
 map, select, inject, grep, find_all, include?
                 and more
Testing
require 'test/unit'

class TestHtmlParser < Test::Unit::TestCase

      must “find all imgs” do
          parser = HtmlParser.new '<div class='a'> <br/> <img src='img1.jpg'>n
                                   <p><img src='img2.jpg'></body>'
          assert_equal parser.parse_imgs, ['img1.jpg','img2.jpg']
      end
end

class HtmlParser

      def initialize html_doc
           @content = html_doc
      end

      def parse_imgs
          @content.scan(/imgs+src='(.+?)'/)
      end
end
Standard Library

● erb - .rhtml
● sockets

● threads

● html/xml parser

● ftp, http, imap, pop3, smtp

● tk

● pstore
And Gems!

$ gem install rails

$ gem install rspec

$ gem search twitter

 13,007 gems and counting!
Productivity and fun

    And that's it!



       Duda Dornelles
 dudassdornelles@gmail.com

Mais conteúdo relacionado

Mais procurados

Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
Ben James
 
Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)
brian d foy
 
Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 

Mais procurados (19)

Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Rails 2010 Workshop
Rails 2010 WorkshopRails 2010 Workshop
Rails 2010 Workshop
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
Metaprogramming and Folly
Metaprogramming and FollyMetaprogramming and Folly
Metaprogramming and Folly
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
 
Designing with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf IndiaDesigning with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf India
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 

Semelhante a A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles

Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
ConFoo
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
Wen-Tien Chang
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 

Semelhante a A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles (20)

Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Ruby
RubyRuby
Ruby
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
Dsl
DslDsl
Dsl
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Language supports it
Language supports itLanguage supports it
Language supports it
 
Why ruby
Why rubyWhy ruby
Why ruby
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 

Mais de Tchelinux

Bikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio Grande
Bikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio GrandeBikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio Grande
Bikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio Grande
Tchelinux
 
A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...
A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...
A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...
Tchelinux
 

Mais de Tchelinux (20)

Do Zero ao YouTube em menos de 10 softwares livres - Vinícius Alves Hax - Tch...
Do Zero ao YouTube em menos de 10 softwares livres - Vinícius Alves Hax - Tch...Do Zero ao YouTube em menos de 10 softwares livres - Vinícius Alves Hax - Tch...
Do Zero ao YouTube em menos de 10 softwares livres - Vinícius Alves Hax - Tch...
 
Insegurança na Internet - Diego Luiz Silva da Costa - Tchelinux 2019 Rio Grande
Insegurança na Internet - Diego Luiz Silva da Costa - Tchelinux 2019 Rio GrandeInsegurança na Internet - Diego Luiz Silva da Costa - Tchelinux 2019 Rio Grande
Insegurança na Internet - Diego Luiz Silva da Costa - Tchelinux 2019 Rio Grande
 
Explorando Editores de Texto Open Source - Gabriel Prestes Ritta - Tchelinux ...
Explorando Editores de Texto Open Source - Gabriel Prestes Ritta - Tchelinux ...Explorando Editores de Texto Open Source - Gabriel Prestes Ritta - Tchelinux ...
Explorando Editores de Texto Open Source - Gabriel Prestes Ritta - Tchelinux ...
 
Desenvolvendo Jogos com PyGame - Jerônimo Medina Madruga - Tchelinux 2019 Rio...
Desenvolvendo Jogos com PyGame - Jerônimo Medina Madruga - Tchelinux 2019 Rio...Desenvolvendo Jogos com PyGame - Jerônimo Medina Madruga - Tchelinux 2019 Rio...
Desenvolvendo Jogos com PyGame - Jerônimo Medina Madruga - Tchelinux 2019 Rio...
 
Me formei. E agora? - Matheus Cezar - Tchelinux 2019 Rio Grande
Me formei. E agora? - Matheus Cezar - Tchelinux 2019 Rio GrandeMe formei. E agora? - Matheus Cezar - Tchelinux 2019 Rio Grande
Me formei. E agora? - Matheus Cezar - Tchelinux 2019 Rio Grande
 
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
 
Shell Script: Seu melhor amigo na automatização de instalações e configuraçõe...
Shell Script: Seu melhor amigo na automatização de instalações e configuraçõe...Shell Script: Seu melhor amigo na automatização de instalações e configuraçõe...
Shell Script: Seu melhor amigo na automatização de instalações e configuraçõe...
 
WebRTC: Comunicação aberta em tempo real - Nelson Dutra Junior - Tchelinux 20...
WebRTC: Comunicação aberta em tempo real - Nelson Dutra Junior - Tchelinux 20...WebRTC: Comunicação aberta em tempo real - Nelson Dutra Junior - Tchelinux 20...
WebRTC: Comunicação aberta em tempo real - Nelson Dutra Junior - Tchelinux 20...
 
Introdução à programação funcional com Clojure - Victor Hechel Colares - Tche...
Introdução à programação funcional com Clojure - Victor Hechel Colares - Tche...Introdução à programação funcional com Clojure - Victor Hechel Colares - Tche...
Introdução à programação funcional com Clojure - Victor Hechel Colares - Tche...
 
Construindo um Data Warehouse - Vítor Resing Plentz - Tchelinux 2019 Rio Grande
Construindo um Data Warehouse - Vítor Resing Plentz - Tchelinux 2019 Rio GrandeConstruindo um Data Warehouse - Vítor Resing Plentz - Tchelinux 2019 Rio Grande
Construindo um Data Warehouse - Vítor Resing Plentz - Tchelinux 2019 Rio Grande
 
Bikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio Grande
Bikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio GrandeBikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio Grande
Bikeshedding - Márcio Josué Ramos Torres - Tchelinux 2019 Rio Grande
 
Produção de textos com Latex - Samuel Francisco Ferrigo - Tchelinux Caxias do...
Produção de textos com Latex - Samuel Francisco Ferrigo - Tchelinux Caxias do...Produção de textos com Latex - Samuel Francisco Ferrigo - Tchelinux Caxias do...
Produção de textos com Latex - Samuel Francisco Ferrigo - Tchelinux Caxias do...
 
A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...
A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...
A tecnologia no futuro e nas mãos de quem ela estará - Jaqueline Trevizan, Ne...
 
oVirt uma solução de virtualização distribuída opensource - Daniel Lara - Tch...
oVirt uma solução de virtualização distribuída opensource - Daniel Lara - Tch...oVirt uma solução de virtualização distribuída opensource - Daniel Lara - Tch...
oVirt uma solução de virtualização distribuída opensource - Daniel Lara - Tch...
 
Sistemas Embarcados e Buildroot - Renato Severo - Tchelinux Caxias do Sul 2019
Sistemas Embarcados e Buildroot - Renato Severo - Tchelinux Caxias do Sul 2019Sistemas Embarcados e Buildroot - Renato Severo - Tchelinux Caxias do Sul 2019
Sistemas Embarcados e Buildroot - Renato Severo - Tchelinux Caxias do Sul 2019
 
Com que ônibus eu vou? Uma gentil introdução ao Python.
Com que ônibus eu vou? Uma gentil introdução ao Python.Com que ônibus eu vou? Uma gentil introdução ao Python.
Com que ônibus eu vou? Uma gentil introdução ao Python.
 
O TCC... um dia ele chega! (The beautiful and easy LaTeX way.
O TCC... um dia ele chega! (The beautiful and easy LaTeX way.O TCC... um dia ele chega! (The beautiful and easy LaTeX way.
O TCC... um dia ele chega! (The beautiful and easy LaTeX way.
 
Não deixe para testar depois o que você pode testar antes.
Não deixe para testar depois o que você pode testar antes. Não deixe para testar depois o que você pode testar antes.
Não deixe para testar depois o que você pode testar antes.
 
Desenvolvendo jogos com pygame
Desenvolvendo jogos com pygameDesenvolvendo jogos com pygame
Desenvolvendo jogos com pygame
 
Essa câmera faz fotos muito boas, né?
Essa câmera faz fotos muito boas, né?Essa câmera faz fotos muito boas, né?
Essa câmera faz fotos muito boas, né?
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles

  • 1.
  • 3. Clean, Elegant and Meaningful Syntax
  • 4. test_string = 'string for test' puts 'matched' if test_string.match 'string' files = Dir['*.txt'] for file in files file_ref = open file file_ref.each_line { |line| puts line.reverse.upcase } end
  • 5. Everything is an Object 10.times { puts “Hello World!” } “Hello World!”.methods
  • 6. Dynamic Typing, Duck Typing and Open Classes
  • 7. a_variable = 'a b c'.split(' ') #=> ['a','b','c'] a_variable = a_variable.join(' ') #=> 'a b c' def a_function object_par puts object_par.crazy_method end a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array class Array def crazy_method return 'crazy method for an array' end end a_function [1,2,3] #=> puts 'crazy method for an array'
  • 8. a_variable = 'a b c'.split(' ') #=> ['a','b','c'] a_variable = a_variable.join(' ') #=> 'a b c' def a_function object_par puts object_par.crazy_method end a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array class Array def crazy_method return 'crazy method for an array' end end a_function [1,2,3] #=> puts 'crazy method for an array'
  • 9. def a_function object_par puts object_par.crazy_method end some_obj = SomeClass.new a_function some_obj #=> error: undefined method 'crazy_method' for class SomeClass def some_obj.crazy_method return 'this is a crazy feature' end a_function some_obj #=> puts 'this is a crazy_feature'
  • 10. def a_function object_par puts object_par.crazy_method end some_obj = SomeClass.new a_function some_obj #=> error: undefined method 'crazy_method' for class SomeClass def some_obj.crazy_method return 'this is a crazy feature' end a_function some_obj #=> puts 'this is a crazy_feature'
  • 11. "if it walks like a duck and quacks like a duck, then it is a duck”
  • 13. def square an_array return an_array.map { |e| e*e } end lines_of_a_doc.each_with_index do |line,i| if i.even? then puts 'even line: #{line}' else puts 'odd line: ' + line end end
  • 14. [1,2,3,4].select { |e| e.even? } #=> [2,4] [1,2,3,4].collect { |e| e.even? } #=> [true,false,true,false] [1,2,3,4].inject(0) { |sum,e| sum += e } #=> 10
  • 15. def my_for n n.times { |n| yield(n) } end my_for 3 { |i| puts i } #=> 1 #=> 2 #=> 3
  • 17. class Books < Collection def initialize @books = SomeReader.new('some_file_with_books').get_books end include Enumerable def each @books.each { |book| yield(book) } end end Class Books now have map, select, inject, grep, find_all, include? and more
  • 19. require 'test/unit' class TestHtmlParser < Test::Unit::TestCase must “find all imgs” do parser = HtmlParser.new '<div class='a'> <br/> <img src='img1.jpg'>n <p><img src='img2.jpg'></body>' assert_equal parser.parse_imgs, ['img1.jpg','img2.jpg'] end end class HtmlParser def initialize html_doc @content = html_doc end def parse_imgs @content.scan(/imgs+src='(.+?)'/) end end
  • 20. Standard Library ● erb - .rhtml ● sockets ● threads ● html/xml parser ● ftp, http, imap, pop3, smtp ● tk ● pstore
  • 21. And Gems! $ gem install rails $ gem install rspec $ gem search twitter 13,007 gems and counting!
  • 22. Productivity and fun And that's it! Duda Dornelles dudassdornelles@gmail.com