├── .gitignore ├── Gemfile ├── Gemfile.lock ├── LICENSE ├── README.md ├── basico ├── Estatica.java ├── Imutavel.java ├── backtrace.rb ├── backtraceless.rb ├── capture.rb ├── captureif.rb ├── case.rb ├── caseprec.rb ├── casetype.rb ├── catchthrow.rb ├── cause.rb ├── customexceptions.rb ├── dup2.rb ├── dup22.rb ├── elsif.rb ├── encodingmeth.rb ├── exc.rb ├── exc2.rb ├── exc3.rb ├── exc4.rb ├── for.rb ├── for2.rb ├── heredoc.rb ├── heredoc_interpolation.rb ├── heredoc_line_spaces.rb ├── heredoc_method.rb ├── heredoc_spaces.rb ├── heredoc_squiggly.rb ├── high.rb ├── if.rb ├── lambret.rb ├── minmax.rb ├── next.rb ├── not_aligned_working.rb ├── not_aligned_working_warning.rb ├── opts.rb ├── pattern_matching.rb ├── pattern_matching_array.rb ├── pattern_matching_arrow.rb ├── pattern_matching_hashes.rb ├── pattern_matching_ignore.rb ├── pattern_matching_pin.rb ├── pattern_matching_splat.rb ├── procret.rb ├── raise.rb ├── redo.rb ├── rescue.rb ├── retry.rb ├── string_bench.rb ├── strings.rb ├── tipagem_fraca.php ├── union_bench.rb ├── until.rb └── while.rb ├── c ├── Makefile ├── curso.c ├── curso.o ├── curso.so ├── extconf.rb ├── hora │ ├── fiddle.rb │ ├── hora.c │ ├── hora.h │ ├── hora.o │ ├── libhora.so │ ├── main │ └── main.c └── old_files │ ├── curso1.c │ ├── curso2.c │ ├── curso3.c │ └── curso4.c ├── classes ├── CarroEstatico.java ├── ancestors.rb ├── autodestruct.rb ├── caixa1.rb ├── caixa2.rb ├── caixa3.rb ├── caixa4.rb ├── caixa5.rb ├── caixa6.rb ├── carro.cpp ├── carro1.rb ├── carro10.rb ├── carro11.rb ├── carro12.rb ├── carro2.rb ├── carro3.rb ├── carro4.rb ├── carro5.rb ├── carro6.rb ├── carro7.rb ├── carro8.rb ├── carro9.rb ├── carro_safe.rb ├── classvar1.rb ├── classvar2.rb ├── classvar3.rb ├── classvar4.rb ├── closures.rb ├── deep.rb ├── descendants.rb ├── destrutor.rb ├── dsl.rb ├── dup.rb ├── fluent.rb ├── forward.rb ├── ghost.rb ├── hooksmeth.rb ├── initializecopy.rb ├── insmethinst.rb ├── methalias.rb ├── methmissing.rb ├── method_missing.rb ├── pcm2_static.rb ├── pcm_static.rb ├── self_static.rb ├── shallow.rb ├── subclasses.rb ├── superclasses.rb ├── supermeth.rb └── wrong_static.rb ├── database ├── alunos ├── alunos.sqlite3 ├── db1.rb ├── db2.rb ├── db3.rb ├── db4.rb ├── db5.rb ├── db6.rb ├── db7.rb ├── db8.rb └── db9.rb ├── docs ├── rdoc │ ├── carro.rb │ ├── carro_complete.rb │ └── doc │ │ ├── Carro.html │ │ ├── Fusca.html │ │ ├── created.rid │ │ ├── css │ │ ├── fonts.css │ │ └── rdoc.css │ │ ├── fonts │ │ ├── Lato-Light.ttf │ │ ├── Lato-LightItalic.ttf │ │ ├── Lato-Regular.ttf │ │ ├── Lato-RegularItalic.ttf │ │ ├── SourceCodePro-Bold.ttf │ │ └── SourceCodePro-Regular.ttf │ │ ├── images │ │ ├── add.png │ │ ├── arrow_up.png │ │ ├── brick.png │ │ ├── brick_link.png │ │ ├── bug.png │ │ ├── bullet_black.png │ │ ├── bullet_toggle_minus.png │ │ ├── bullet_toggle_plus.png │ │ ├── date.png │ │ ├── delete.png │ │ ├── find.png │ │ ├── loadingAnimation.gif │ │ ├── macFFBgHack.png │ │ ├── package.png │ │ ├── page_green.png │ │ ├── page_white_text.png │ │ ├── page_white_width.png │ │ ├── plugin.png │ │ ├── ruby.png │ │ ├── tag_blue.png │ │ ├── tag_green.png │ │ ├── transparent.png │ │ ├── wrench.png │ │ ├── wrench_orange.png │ │ └── zoom.png │ │ ├── index.html │ │ ├── js │ │ ├── darkfish.js │ │ ├── navigation.js │ │ ├── navigation.js.gz │ │ ├── search.js │ │ ├── search_index.js │ │ ├── search_index.js.gz │ │ ├── searcher.js │ │ └── searcher.js.gz │ │ └── table_of_contents.html └── yard │ ├── .yardoc │ ├── checksums │ ├── complete │ ├── object_types │ ├── objects │ │ └── root.dat │ └── proxy_types │ ├── carro.rb │ ├── carro_complete.rb │ └── doc │ ├── Carro.html │ ├── Fusca.html │ ├── _index.html │ ├── class_list.html │ ├── css │ ├── common.css │ ├── full_list.css │ └── style.css │ ├── file_list.html │ ├── frames.html │ ├── index.html │ ├── js │ ├── app.js │ ├── full_list.js │ └── jquery.js │ ├── method_list.html │ └── top-level-namespace.html ├── gc ├── gc1.rb ├── gc2.c ├── gc2.rb ├── gc3 ├── gc3.c ├── gc4.c ├── gc5 ├── gc5.c ├── gc6 ├── gc6.c ├── null ├── null.c ├── str_bench.rb └── sym_gc.rb ├── gems ├── Fib.java ├── load2.rb ├── memo.cache ├── memo1.rb ├── memo2.rb ├── memo3.rb ├── portnum │ ├── .gitignore │ ├── Gemfile │ ├── README.md │ ├── Rakefile │ ├── bin │ │ ├── console │ │ └── setup │ ├── lib │ │ ├── portnum.rb │ │ └── portnum │ │ │ └── version.rb │ ├── portnum.gemspec │ └── test │ │ ├── portnum_test.rb │ │ └── test_helper.rb ├── tco1.rb ├── tco2.rb └── tco3.rb ├── io ├── 1.txt ├── 2.txt ├── 3.txt ├── README ├── RPCClient.java ├── alunos.html ├── alunos.xml ├── alunos.xsl ├── bytes.rb ├── chars.rb ├── copy.rb ├── csv_read1.rb ├── csv_read2.rb ├── csv_read3.rb ├── csv_types.csv ├── csv_write.rb ├── data.rb ├── faraday.rb ├── flip_flop.rb ├── flip_flop_test.txt ├── ftp.rb ├── http1.rb ├── http10.rb ├── http11.rb ├── http2.rb ├── http3.rb ├── http4.rb ├── http5.rb ├── http6.rb ├── http7.rb ├── http8.rb ├── http9.rb ├── httparty.rb ├── https.rb ├── io1.rb ├── io2.rb ├── io3.rb ├── io4.rb ├── io7.rb ├── leryaml.rb ├── nome.rb ├── nome.sh ├── novo_teste.txt ├── pop3.rb ├── rexml.rb ├── rpcclient.php ├── rpcclient.py ├── rpcclient.rb ├── rpcserver.rb ├── smtp.rb ├── sock.rb ├── ssh.rb ├── tcpclient.rb ├── tcpserver.rb ├── tcpserver2.rb ├── tcpserver3.rb ├── teste.txt ├── teste.yml ├── teste.zip ├── teste2.yml ├── teste3.yml ├── teste4.yml ├── teste5.yml ├── teste6.yml ├── txts │ ├── 1.txt │ ├── 2.txt │ └── 3.txt ├── udpclient.rb ├── udpserver.rb ├── webrick.rb ├── xml2.rb ├── xml3.rb ├── xml4.rb ├── xml5.rb ├── xml6.rb └── xslt.rb ├── jruby ├── Carro.java ├── Double.java ├── carro_java.rb ├── doublejava.rb ├── gui.rb └── jruby.rb ├── modulos ├── Namespace.java ├── ancestors.rb ├── binding.rb ├── binding2.rb ├── com │ └── eustaquiorangel │ │ ├── gaucho │ │ └── Pessoa.java │ │ └── paulista │ │ └── Pessoa.java ├── inception.rb ├── inception1.rb ├── inception2.rb ├── interface.rb ├── mod1.rb ├── mod2.rb ├── mod3.rb ├── mod4.rb ├── mod5.rb ├── mod6.rb ├── mod7.rb ├── overmod.rb ├── prepend.rb ├── refinements.rb └── tpoint.rb ├── rake ├── 1.txt ├── 2.txt ├── 3.txt ├── Rakefile ├── Rakefile-1 ├── Rakefile-2 ├── Rakefile-3 ├── Rakefile-4 ├── Rakefile-5 ├── Rakefile-6 ├── Rakefile-7 ├── Rakefile-8 ├── a.txt ├── b.txt ├── c.txt └── dependent.rake ├── rbs ├── Steepfile ├── Steepfile.init ├── carro.naked.rbs ├── carro.rb └── carro.rbs ├── testing ├── Guardfile ├── calc.rb ├── calc_bench_spec.rb ├── calc_spec.rb ├── calc_spec2.rb ├── calc_spec3.rb ├── calc_spec_reporters.rb ├── calc_test.rb ├── calc_test2.rb ├── calc_test_not.rb ├── calc_test_omit.rb ├── calc_test_pend.rb ├── carro.rb ├── minitest1.rb └── spec │ └── calc_spec.rb └── threads ├── bench1.rb ├── bench2.rb ├── cont.rb ├── fiber_names.rb ├── fibers1.rb ├── fibers2.rb ├── fibers3.rb ├── fibers4.rb ├── fibers5.rb ├── fibers6.rb ├── fibers7.rb ├── fifo.rb ├── par.rb ├── par2.rb ├── par3.rb ├── par4.rb ├── parsample.rb ├── rac1.rb ├── rac2.rb ├── rac3.rb ├── rac4.rb ├── rac5.rb ├── rac6.rb ├── rac7.rb ├── rac8.rb ├── rac9.rb ├── ractors.rb ├── rubyproftest.rb ├── thr1.rb ├── thr11.rb ├── thr2.rb ├── thr3.rb ├── thr4.rb ├── thr5.rb ├── thr6.rb ├── thr7.rb ├── thr71.rb ├── thr72.rb ├── thr8.rb └── thr9.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.jar 3 | .nvimlog 4 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | ruby '3.3.0' 3 | 4 | gem 'parallel' 5 | gem 'nokogiri' 6 | gem 'net-ssh' 7 | gem 'highline' 8 | gem 'base64' 9 | gem 'async-io' 10 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | async (2.8.1) 5 | console (~> 1.10) 6 | fiber-annotation 7 | io-event (~> 1.1) 8 | timers (~> 4.1) 9 | async-io (1.41.0) 10 | async 11 | base64 (0.2.0) 12 | console (1.23.4) 13 | fiber-annotation 14 | fiber-local 15 | json 16 | fiber-annotation (0.2.0) 17 | fiber-local (1.0.0) 18 | highline (3.0.1) 19 | io-event (1.4.4) 20 | json (2.7.1) 21 | mini_portile2 (2.8.5) 22 | net-ssh (7.2.1) 23 | nokogiri (1.16.2) 24 | mini_portile2 (~> 2.8.2) 25 | racc (~> 1.4) 26 | nokogiri (1.16.2-x86_64-linux) 27 | racc (~> 1.4) 28 | parallel (1.24.0) 29 | racc (1.7.3) 30 | timers (4.3.5) 31 | 32 | PLATFORMS 33 | ruby 34 | x86_64-linux 35 | 36 | DEPENDENCIES 37 | async-io 38 | base64 39 | highline 40 | net-ssh 41 | nokogiri 42 | parallel 43 | 44 | RUBY VERSION 45 | ruby 3.3.0p0 46 | 47 | BUNDLED WITH 48 | 2.5.3 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arquivos do livro "Conhecendo Ruby" 2 | 3 | Aqui você vai encontrar os arquivos do livro "Conhecendo Ruby", publicado em 4 | [http://leanpub.com/conhecendo-ruby](http://leanpub.com/conhecendo-ruby). 5 | -------------------------------------------------------------------------------- /basico/Estatica.java: -------------------------------------------------------------------------------- 1 | public class Estatica { 2 | public static void main(String args[]) { 3 | String v = "teste"; 4 | System.out.println(v); 5 | v = 1; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /basico/Imutavel.java: -------------------------------------------------------------------------------- 1 | public class Imutavel { 2 | public static void main(String args[]) { 3 | String mutable = "conteúdo original"; 4 | mutable = "essa string é mutável!"; 5 | 6 | final String immutable = "conteúdo original"; 7 | immutable = "essa string é imutável!"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /basico/backtrace.rb: -------------------------------------------------------------------------------- 1 | numero1 = 1 2 | numero2 = "dois" 3 | begin 4 | puts numero1 + numero2 5 | rescue => exception 6 | puts "Ops, problemas aqui (#{exception.class}), vou tentar de novo." 7 | puts exception.backtrace 8 | numero2 = 2 9 | retry 10 | end 11 | -------------------------------------------------------------------------------- /basico/backtraceless.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | 3 | class CustomException < StandardError 4 | end 5 | 6 | Benchmark.bm do |bm| 7 | bm.report('com backtrace') do 8 | 100_000.times do 9 | raise CustomException, 'Deu erro aqui' 10 | rescue 11 | end 12 | end 13 | 14 | bm.report('sem backtrace') do 15 | 100_000.times do 16 | raise CustomException, 'Deu erro aqui', [] 17 | rescue 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /basico/capture.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def teste(qtde) 3 | qtde.times { puts "teste!" } 4 | end 5 | end 6 | 7 | t = Teste.new 8 | m = t.method(:teste) 9 | p m 10 | m.(3) 11 | p m.to_proc 12 | -------------------------------------------------------------------------------- /basico/captureif.rb: -------------------------------------------------------------------------------- 1 | i = 10 2 | 3 | result = 4 | if i > 10 5 | "maior que 10" 6 | elsif i == 10 7 | "igual a 10" 8 | else 9 | "menor que 10" 10 | end 11 | 12 | result 13 | -------------------------------------------------------------------------------- /basico/case.rb: -------------------------------------------------------------------------------- 1 | i = 10 2 | 3 | case i 4 | when 0..5 5 | puts "entre 0 e 5" 6 | when 6..10 7 | puts "entre 6 e 10" 8 | else 9 | puts "hein?" 10 | end 11 | -------------------------------------------------------------------------------- /basico/caseprec.rb: -------------------------------------------------------------------------------- 1 | i = 10 2 | 3 | case i 4 | when Integer 5 | puts "Número!" 6 | when (0..100) 7 | puts "entre 0 e 100" 8 | end 9 | -------------------------------------------------------------------------------- /basico/casetype.rb: -------------------------------------------------------------------------------- 1 | i = 10 2 | 3 | case i 4 | when Integer 5 | puts "Número!" 6 | when String 7 | puts "String!" 8 | else 9 | puts "hein???" 10 | end 11 | -------------------------------------------------------------------------------- /basico/catchthrow.rb: -------------------------------------------------------------------------------- 1 | def get_input 2 | puts "Digite algo (número termina):" 3 | resp = gets 4 | 5 | throw :end_of_response, resp if resp.chomp.match? /^\d+$/ 6 | 7 | resp 8 | end 9 | 10 | num = catch(:end_of_response) do 11 | while true 12 | get_input 13 | end 14 | end 15 | 16 | puts "Terminado com: #{num}" 17 | -------------------------------------------------------------------------------- /basico/cause.rb: -------------------------------------------------------------------------------- 1 | begin 2 | begin 3 | raise 'foo' 4 | rescue Exception => foo 5 | raise 'bar' 6 | end 7 | rescue Exception => bar 8 | puts "a causa de #{bar} foi #{bar.cause}" 9 | end 10 | -------------------------------------------------------------------------------- /basico/customexceptions.rb: -------------------------------------------------------------------------------- 1 | class NameNotEqual < StandardError 2 | def initialize(current, expected) 3 | super "Você digitou um nome inválido (#{current})! Era esperado #{expected}." 4 | end 5 | end 6 | 7 | begin 8 | correct = "eustaquio" 9 | puts "Digite o meu nome: " 10 | name = gets.chomp 11 | 12 | raise NameNotEqual.new(name, correct) if name != correct 13 | 14 | puts "Digitou correto!" 15 | rescue NameNotEqual => e 16 | puts e 17 | end 18 | -------------------------------------------------------------------------------- /basico/dup2.rb: -------------------------------------------------------------------------------- 1 | dup = ->(x) { x * 2 } 2 | sqr = ->(x) { x ** 2 } 3 | dup2 = dup >> sqr 4 | 5 | puts dup2.call(2) 6 | 7 | # seria o mesmo que 8 | puts sqr.call(dup.call(2)) 9 | -------------------------------------------------------------------------------- /basico/dup22.rb: -------------------------------------------------------------------------------- 1 | dup = ->(x) { x * 2 } 2 | sqr = ->(x) { x ** 2 } 3 | half = ->(x) { x / 2 } 4 | tenp = ->(x) { x * 0.1 } 5 | crazy = dup >> sqr >> half >> tenp 6 | 7 | puts crazy.call(2) 8 | 9 | -------------------------------------------------------------------------------- /basico/elsif.rb: -------------------------------------------------------------------------------- 1 | i = 10 2 | 3 | if i > 10 4 | puts "maior que 10" 5 | elsif i == 10 6 | puts "igual a 10" 7 | else 8 | puts "menor que 10" 9 | end 10 | -------------------------------------------------------------------------------- /basico/encodingmeth.rb: -------------------------------------------------------------------------------- 1 | module Enumerable 2 | def ∑ 3 | self.inject { |memo, val| memo += val } 4 | end 5 | end 6 | 7 | puts [1, 2, 3].∑ 8 | puts (0..3).∑ 9 | -------------------------------------------------------------------------------- /basico/exc.rb: -------------------------------------------------------------------------------- 1 | begin 2 | numero = 1 3 | string = "oi" 4 | numero + string 5 | rescue StandardError => exception 6 | puts "Ocorreu um erro: #{exception}" 7 | end 8 | -------------------------------------------------------------------------------- /basico/exc2.rb: -------------------------------------------------------------------------------- 1 | begin 2 | numero = 1 3 | string = "oi" 4 | numero + string 5 | rescue => exception 6 | puts "Ocorreu um erro do tipo #{exception.class}: #{exception}" 7 | end 8 | -------------------------------------------------------------------------------- /basico/exc3.rb: -------------------------------------------------------------------------------- 1 | begin 2 | numero = 1 3 | string = "oi" 4 | numero + string 5 | rescue => exception 6 | puts "Ocorreu um erro do tipo #{exception.class}: #{exception}" 7 | ensure 8 | puts "Lascou tudo." 9 | end 10 | puts "Fim de programa." 11 | -------------------------------------------------------------------------------- /basico/exc4.rb: -------------------------------------------------------------------------------- 1 | begin 2 | numero = 1 3 | string = "oi" 4 | numero + string 5 | rescue => exception 6 | puts "Ocorreu um erro do tipo #{exception.class}: #{exception}" 7 | puts msg 8 | ensure 9 | puts "Lascou tudo." 10 | end 11 | puts "Fim de programa." 12 | -------------------------------------------------------------------------------- /basico/for.rb: -------------------------------------------------------------------------------- 1 | for i in (0..5) 2 | puts i 3 | end 4 | -------------------------------------------------------------------------------- /basico/for2.rb: -------------------------------------------------------------------------------- 1 | for i in (0..5) 2 | break if i == 3 3 | puts i 4 | end 5 | -------------------------------------------------------------------------------- /basico/heredoc.rb: -------------------------------------------------------------------------------- 1 | str = < exc 46 | STDERR.puts "Erro: #{exc}\n\n" 47 | STDERR.puts parser.help 48 | end 49 | -------------------------------------------------------------------------------- /basico/pattern_matching.rb: -------------------------------------------------------------------------------- 1 | valores = [1, 2, 3] 2 | 3 | case valores 4 | in [a] 5 | puts "O valor é #{a}" 6 | in [a, b] 7 | puts "Os valores são: #{a} e #{b}" 8 | in [a, b, c] 9 | puts "Os valores são: #{a}, #{b} e #{c}" 10 | end 11 | -------------------------------------------------------------------------------- /basico/pattern_matching_array.rb: -------------------------------------------------------------------------------- 1 | traducoes = [:br, 'Bom dia', :en, 'Good morning'] 2 | 3 | case traducoes 4 | in [:br, texto_br, :es, texto_es] 5 | puts "'#{texto_br}' em Espanhol é '#{texto_es}'" 6 | in [:br, texto_br, :en, texto_en] 7 | puts "'#{texto_br}' em Inglês é '#{texto_en}'" 8 | else 9 | puts "Sem tradução" 10 | end 11 | -------------------------------------------------------------------------------- /basico/pattern_matching_arrow.rb: -------------------------------------------------------------------------------- 1 | traducoes = [:br, 'Bom dia', :en, 'Good morning'] 2 | 3 | case traducoes 4 | in [Symbol, String, Symbol, String] => found 5 | p found 6 | end 7 | -------------------------------------------------------------------------------- /basico/pattern_matching_hashes.rb: -------------------------------------------------------------------------------- 1 | traducoes = { original: :br, texto_original: 'Bom dia', destino: :en, texto_traduzido: 'Good morning' } 2 | 3 | case traducoes 4 | in { original: :br, texto_original: texto_original, destino: :es, texto_traduzido: texto_traduzido } 5 | puts "'#{texto_original}' em Espanhol é '#{texto_traduzido}'" 6 | in { original: :br, texto_original: texto_original, destino: :en, texto_traduzido: texto_traduzido } 7 | puts "'#{texto_original}' em Inglês é '#{texto_traduzido}'" 8 | else 9 | puts "Sem tradução" 10 | end 11 | 12 | -------------------------------------------------------------------------------- /basico/pattern_matching_ignore.rb: -------------------------------------------------------------------------------- 1 | valores = [1, 2, 3] 2 | 3 | case valores 4 | in [_, dois, _] 5 | puts "O segundo valor é #{dois}" 6 | end 7 | -------------------------------------------------------------------------------- /basico/pattern_matching_pin.rb: -------------------------------------------------------------------------------- 1 | case [1, 2, 2] 2 | in [a, b, ^b] 3 | puts "Os valores com pin são: #{a} e #{b}" 4 | end 5 | -------------------------------------------------------------------------------- /basico/pattern_matching_splat.rb: -------------------------------------------------------------------------------- 1 | valores = [1, 2, 3] 2 | 3 | case valores 4 | in [a, *b] 5 | puts "O valor de a é #{a}" 6 | puts "b vale:" 7 | p b 8 | end 9 | -------------------------------------------------------------------------------- /basico/procret.rb: -------------------------------------------------------------------------------- 1 | def testando_proc 2 | p = Proc.new { return "Bum!" } 3 | p.call 4 | "Nunca imprime isso." 5 | end 6 | 7 | puts testando_proc 8 | -------------------------------------------------------------------------------- /basico/raise.rb: -------------------------------------------------------------------------------- 1 | numero1 = 1 2 | numero2 = 1 3 | 4 | begin 5 | puts numero1 + numero2 6 | raise Exception.new("esperava 3") if numero1+numero2!=3 7 | rescue => exception 8 | puts "Ops, problemas aqui (#{exception.class}), vou tentar de novo." 9 | end 10 | -------------------------------------------------------------------------------- /basico/redo.rb: -------------------------------------------------------------------------------- 1 | for i in (0..5) 2 | redo if i == 3 3 | puts i 4 | end 5 | -------------------------------------------------------------------------------- /basico/rescue.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | 3 | limit = 1_000_000 4 | str = nil 5 | 6 | Benchmark.bm do |x| 7 | x.report("rescue") do 8 | limit.times { str.upcase rescue nil } 9 | end 10 | 11 | x.report("ternário") do 12 | limit.times { str ? str.upcase : nil } 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /basico/retry.rb: -------------------------------------------------------------------------------- 1 | numero1 = 1 2 | numero2 = "dois" 3 | begin 4 | puts numero1 + numero2 5 | rescue => exception 6 | puts "Ops, problemas aqui (#{exception.class}), vou tentar de novo." 7 | numero2 = 2 8 | retry 9 | end 10 | -------------------------------------------------------------------------------- /basico/string_bench.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | 3 | Benchmark.bm do |bm| 4 | bm.report('alocando strings') do 5 | 1_000_000.times { s = "alocando!" } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /basico/strings.rb: -------------------------------------------------------------------------------- 1 | puts "o céu é 'azul'" 2 | puts "o céu é \"azul\"" 3 | puts 'o céu é "azul"' 4 | puts 'o céu é \'azul\'' 5 | -------------------------------------------------------------------------------- /basico/tipagem_fraca.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /basico/union_bench.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | 3 | a1 = ["a", "b", "c"] 4 | a2 = ["c", "d", "a"] 5 | a3 = ["a", "a", "b", "b", "c", "c", "d", "e"] 6 | a4 = ["a", "b", "d"] 7 | nt = 10_000 8 | 9 | Benchmark.bm do |bm| 10 | bm.report('com |') do 11 | nt.times { a1 | a2 } 12 | end 13 | bm.report('com union') do 14 | nt.times { a1.union a2 } 15 | end 16 | bm.report('com -') do 17 | nt.times { a3 - a4 } 18 | end 19 | bm.report('com difference') do 20 | nt.times { a3.difference a4 } 21 | end 22 | bm.report('com &') do 23 | nt.times { a1 & a2 } 24 | end 25 | bm.report('com intersection') do 26 | nt.times { a1.intersection a2 } 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /basico/until.rb: -------------------------------------------------------------------------------- 1 | i = 0 2 | 3 | until i==5 4 | puts i 5 | i += 1 6 | end 7 | -------------------------------------------------------------------------------- /basico/while.rb: -------------------------------------------------------------------------------- 1 | i = 0 2 | 3 | while i < 5 4 | puts i 5 | i += 1 6 | end 7 | -------------------------------------------------------------------------------- /c/curso.c: -------------------------------------------------------------------------------- 1 | old_files/curso4.c -------------------------------------------------------------------------------- /c/curso.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/c/curso.o -------------------------------------------------------------------------------- /c/curso.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/c/curso.so -------------------------------------------------------------------------------- /c/extconf.rb: -------------------------------------------------------------------------------- 1 | require "mkmf" 2 | 3 | extension_name = "curso" 4 | dir_config(extension_name) 5 | create_makefile(extension_name) 6 | -------------------------------------------------------------------------------- /c/hora/fiddle.rb: -------------------------------------------------------------------------------- 1 | require "fiddle" 2 | 3 | # carrega a lib compartilhada 4 | libhora = Fiddle.dlopen("./libhora.so") 5 | 6 | # pega uma referência para a função 7 | hora = Fiddle::Function.new(libhora["hora"], [], Fiddle::TYPE_VOIDP) 8 | 9 | # chama a função 10 | puts hora.call 11 | -------------------------------------------------------------------------------- /c/hora/hora.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct tm *get_date_time() { 7 | time_t dt; 8 | struct tm *dc; 9 | time(&dt); 10 | dc = localtime(&dt); 11 | return dc; 12 | } 13 | 14 | char *hora() { 15 | char *str, cur[15]; 16 | str = malloc(sizeof(char) * 15); 17 | struct tm *dc = get_date_time(); 18 | sprintf(cur, "%02d:%02d:%02d", dc->tm_hour, dc->tm_min, dc->tm_sec); 19 | strcpy(str, cur); 20 | return str; 21 | } 22 | -------------------------------------------------------------------------------- /c/hora/hora.h: -------------------------------------------------------------------------------- 1 | #ifndef hora_h__ 2 | #define hora_h__ 3 | 4 | extern char* hora(void); 5 | 6 | #endif // hora_h__ 7 | -------------------------------------------------------------------------------- /c/hora/hora.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/c/hora/hora.o -------------------------------------------------------------------------------- /c/hora/libhora.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/c/hora/libhora.so -------------------------------------------------------------------------------- /c/hora/main: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/c/hora/main -------------------------------------------------------------------------------- /c/hora/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "hora.h" 3 | 4 | int main(void) 5 | { 6 | puts("Teste da lib compartilhada:"); 7 | puts(hora()); 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /c/old_files/curso1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | VALUE modulo, classe; 5 | 6 | void Init_curso(){ 7 | modulo = rb_define_module("Curso"); 8 | classe = rb_define_class_under(modulo, "Horario", rb_cObject); 9 | } 10 | -------------------------------------------------------------------------------- /c/old_files/curso2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | VALUE modulo, classe; 5 | 6 | VALUE t_init(VALUE self, VALUE valor){ 7 | rb_iv_set(self, "@descricao", valor); 8 | return self; 9 | } 10 | 11 | void Init_curso(){ 12 | modulo = rb_define_module("Curso"); 13 | classe = rb_define_class_under(modulo, "Horario", rb_cObject); 14 | rb_define_method(classe,"initialize", t_init, 1); 15 | } 16 | -------------------------------------------------------------------------------- /c/old_files/curso3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | VALUE modulo, classe; 5 | 6 | VALUE t_init(VALUE self, VALUE valor){ 7 | rb_iv_set(self, "@descricao", valor); 8 | return self; 9 | } 10 | 11 | VALUE descricao(VALUE self){ 12 | return rb_iv_get(self, "@descricao"); 13 | } 14 | 15 | void Init_curso(){ 16 | modulo = rb_define_module("Curso"); 17 | classe = rb_define_class_under(modulo, "Horario", rb_cObject); 18 | rb_define_method(classe, "initialize", t_init, 1); 19 | rb_define_method(classe, "descricao", descricao, 0); 20 | } 21 | -------------------------------------------------------------------------------- /c/old_files/curso4.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | VALUE modulo, classe; 5 | 6 | VALUE t_init(VALUE self, VALUE valor){ 7 | rb_iv_set(self, "@descricao", valor); 8 | return self; 9 | } 10 | 11 | VALUE descricao(VALUE self){ 12 | return rb_iv_get(self, "@descricao"); 13 | } 14 | 15 | struct tm *get_date_time() { 16 | time_t dt; 17 | struct tm *dc; 18 | time(&dt); 19 | dc = localtime(&dt); 20 | return dc; 21 | } 22 | 23 | VALUE data(VALUE self) { 24 | char str[30]; 25 | struct tm *dc = get_date_time(); 26 | sprintf(str, "%02d/%02d/%04d", dc->tm_mday, dc->tm_mon + 1, dc->tm_year + 1900); 27 | return rb_str_new2(str); 28 | } 29 | 30 | VALUE hora(VALUE self) { 31 | char str[15]; 32 | struct tm *dc = get_date_time(); 33 | sprintf(str, "%02d:%02d:%02d", dc->tm_hour, dc->tm_min, dc->tm_sec); 34 | return rb_str_new2(str); 35 | } 36 | 37 | void Init_curso() { 38 | modulo = rb_define_module("Curso"); 39 | classe = rb_define_class_under(modulo, "Horario", rb_cObject); 40 | rb_define_method(classe, "initialize", t_init, 1); 41 | rb_define_method(classe, "descricao", descricao, 0); 42 | rb_define_method(classe, "data", data, 0); 43 | rb_define_method(classe, "hora", hora, 0); 44 | } 45 | -------------------------------------------------------------------------------- /classes/CarroEstatico.java: -------------------------------------------------------------------------------- 1 | public class CarroEstatico { 2 | private static int qtde = 0; 3 | 4 | public CarroEstatico() { 5 | ++qtde; 6 | } 7 | 8 | public static int qtde() { 9 | return qtde; 10 | } 11 | 12 | public static void main(String args[]) { 13 | CarroEstatico[] carros = new CarroEstatico[10]; 14 | 15 | for (int i = 0; i < carros.length; i++) { 16 | carros[i] = new CarroEstatico(); 17 | System.out.println(CarroEstatico.qtde() + " carros"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /classes/ancestors.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | end 3 | 4 | p String.ancestors 5 | p Teste.ancestors 6 | -------------------------------------------------------------------------------- /classes/autodestruct.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def apenas_uma_vez 3 | def self.apenas_uma_vez 4 | raise StandardError, "Esse método se destruiu!" 5 | end 6 | 7 | puts "Vou rodar apenas essa vez hein?" 8 | end 9 | end 10 | 11 | teste = Teste.new 12 | teste.apenas_uma_vez 13 | teste.apenas_uma_vez 14 | -------------------------------------------------------------------------------- /classes/caixa1.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | attr_reader :quantidade 3 | 4 | def initialize(quantidade) 5 | @quantidade = quantidade 6 | end 7 | 8 | def to_s 9 | "Quantidade de parafusos na caixa #{self.object_id}: #{@quantidade}" 10 | end 11 | 12 | def +(outra) 13 | CaixaDeParafusos.new(@quantidade + outra.quantidade) 14 | end 15 | end 16 | 17 | caixa1 = CaixaDeParafusos.new(10) 18 | caixa2 = CaixaDeParafusos.new(20) 19 | caixa3 = caixa1 + caixa2 20 | 21 | puts caixa1 22 | puts caixa2 23 | puts caixa3 24 | -------------------------------------------------------------------------------- /classes/caixa2.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | attr_reader :quantidade 3 | 4 | def initialize(quantidade) 5 | @quantidade = quantidade 6 | end 7 | 8 | def to_s 9 | "Quantidade de parafusos na caixa #{self.object_id}: #{@quantidade}" 10 | end 11 | 12 | def +(outra) 13 | CaixaDeParafusos.new(@quantidade + outra.quantidade) 14 | @quantidade = 0 15 | outra.quantidade = 0 16 | end 17 | end 18 | 19 | caixa1 = CaixaDeParafusos.new(10) 20 | caixa2 = CaixaDeParafusos.new(20) 21 | caixa3 = caixa1 + caixa2 22 | 23 | puts caixa1 24 | puts caixa2 25 | puts caixa3 26 | -------------------------------------------------------------------------------- /classes/caixa3.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | protected 3 | attr_writer :quantidade 4 | 5 | public 6 | attr_reader :quantidade 7 | 8 | def initialize(quantidade) 9 | @quantidade = quantidade 10 | end 11 | 12 | def to_s 13 | "Quantidade de parafusos na caixa #{self.object_id}: #{@quantidade}" 14 | end 15 | 16 | def +(outra) 17 | nova = CaixaDeParafusos.new(@quantidade + outra.quantidade) 18 | @quantidade = 0 19 | outra.quantidade = 0 20 | nova 21 | end 22 | end 23 | 24 | caixa1 = CaixaDeParafusos.new(10) 25 | caixa2 = CaixaDeParafusos.new(20) 26 | caixa3 = caixa1 + caixa2 27 | 28 | puts caixa1 29 | puts caixa2 30 | puts caixa3 31 | -------------------------------------------------------------------------------- /classes/caixa4.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | protected 3 | attr_writer :quantidade 4 | 5 | public 6 | attr_reader :quantidade 7 | 8 | def initialize(quantidade) 9 | @quantidade = quantidade 10 | end 11 | 12 | def to_s 13 | "Quantidade de parafusos na caixa #{self.object_id}: #{@quantidade}" 14 | end 15 | 16 | def +(outra) 17 | nova = CaixaDeParafusos.new(@quantidade + outra.quantidade) 18 | @quantidade = 0 19 | outra.quantidade = 0 20 | nova 21 | end 22 | 23 | def /(quantidade) 24 | caixas = Array.new(@quantidade / quantidade, quantidade) 25 | caixas << @quantidade % quantidade if @quantidade % quantidade > 0 26 | @quantidade = 0 27 | caixas.map { |it| CaixaDeParafusos.new(it) } 28 | end 29 | end 30 | 31 | caixa1 = CaixaDeParafusos.new(10) 32 | caixa2 = CaixaDeParafusos.new(20) 33 | caixa3 = caixa1 + caixa2 34 | 35 | puts caixa3 / 8 36 | -------------------------------------------------------------------------------- /classes/caixa5.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | protected 3 | attr_writer :quantidade 4 | 5 | public 6 | attr_reader :quantidade 7 | 8 | def initialize(quantidade) 9 | @quantidade = quantidade 10 | end 11 | 12 | def to_s 13 | "Quantidade de parafusos na caixa #{self.object_id}: #{@quantidade}" 14 | end 15 | 16 | def +(outra) 17 | nova = CaixaDeParafusos.new(@quantidade + outra.quantidade) 18 | @quantidade = 0 19 | outra.quantidade = 0 20 | nova 21 | end 22 | 23 | def /(quantidade) 24 | caixas = Array.new(quantidade, @quantidade / quantidade) 25 | (@quantidade % quantidade).times { |it| caixas[it] += 1 } 26 | @quantidade = 0 27 | caixas.map { |it| CaixaDeParafusos.new(it) } 28 | end 29 | end 30 | 31 | caixa1 = CaixaDeParafusos.new(10) 32 | caixa2 = CaixaDeParafusos.new(20) 33 | caixa3 = caixa1 + caixa2 34 | 35 | puts caixa3 / 4 36 | -------------------------------------------------------------------------------- /classes/caixa6.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | protected 3 | attr_writer :quantidade 4 | 5 | public 6 | attr_reader :quantidade 7 | 8 | def initialize(quantidade) 9 | @quantidade = quantidade 10 | end 11 | 12 | def to_s 13 | "Quantidade de parafusos na caixa #{self.object_id}: #{@quantidade}" 14 | end 15 | 16 | def +(outra) 17 | nova = CaixaDeParafusos.new(@quantidade + outra.quantidade) 18 | @quantidade = 0 19 | outra.quantidade = 0 20 | nova 21 | end 22 | 23 | def /(quantidade) 24 | caixas = Array.new(quantidade, @quantidade / quantidade) 25 | (@quantidade % quantidade).times { |it| caixas[it] += 1 } 26 | @quantidade = 0 27 | caixas.map { |it| CaixaDeParafusos.new(it) } 28 | end 29 | 30 | def -@ 31 | anterior = @quantidade 32 | @quantidade = 1 33 | CaixaDeParafusos.new(anterior - 1) 34 | end 35 | end 36 | 37 | caixa1 = CaixaDeParafusos.new(10) 38 | caixa2 = -caixa1 39 | 40 | puts caixa1 41 | puts caixa2 42 | -------------------------------------------------------------------------------- /classes/carro.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Automovel { 6 | public: 7 | void ligar() { 8 | cout << "ligando o automóvel\n"; 9 | } 10 | }; 11 | 12 | class Radio { 13 | public: 14 | void ligar() { 15 | cout << "ligando o rádio\n"; 16 | } 17 | }; 18 | 19 | class Carro: public Automovel, public Radio { 20 | public: 21 | Carro() {} 22 | }; 23 | 24 | int main() { 25 | Carro carro; 26 | carro.ligar(); // só compila com Automovel::ligar(); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /classes/carro1.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | def initialize(marca, modelo, cor, tanque) 3 | @marca = marca 4 | @modelo = modelo 5 | @cor = cor 6 | @tanque = tanque 7 | end 8 | end 9 | 10 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 11 | p corsa 12 | puts corsa 13 | -------------------------------------------------------------------------------- /classes/carro10.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 14 | end 15 | end 16 | 17 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 18 | gol = Carro.new(:volks, :gol, :azul, 42) 19 | 20 | (class << corsa; self; end).send(:define_method, "multiplica_tanque") do |valor| 21 | @tanque * valor 22 | end 23 | 24 | puts corsa.multiplica_tanque(2) 25 | puts gol.multiplica_tanque(2) 26 | -------------------------------------------------------------------------------- /classes/carro11.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | @@qtde = 0 5 | 6 | def initialize(marca, modelo, cor, tanque) 7 | @marca = marca 8 | @modelo = modelo 9 | @cor = cor 10 | @tanque = tanque 11 | @@qtde += 1 12 | end 13 | 14 | def to_s 15 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 16 | end 17 | 18 | def self.qtde 19 | @@qtde 20 | end 21 | end 22 | 23 | class NovoCarro < Carro 24 | def to_s 25 | "Marca nova:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 26 | end 27 | end 28 | 29 | carro1 = Carro.new(:chevrolet, :corsa, :preto, 50) 30 | carro2 = Carro.new(:chevrolet, :corsa, :prata, 50) 31 | novo_carro = NovoCarro.new(:volks, :gol, :azul, 42) 32 | 33 | puts carro1 34 | puts carro2 35 | puts novo_carro 36 | puts Carro.qtde 37 | puts NovoCarro.qtde 38 | -------------------------------------------------------------------------------- /classes/carro12.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | @@qtde = 0 5 | 6 | def initialize(marca, modelo, cor, tanque) 7 | @marca = marca 8 | @modelo = modelo 9 | @cor = cor 10 | @tanque = tanque 11 | @@qtde += 1 12 | end 13 | 14 | def to_s 15 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 16 | end 17 | end 18 | 19 | class NovoCarro < Carro 20 | def to_s 21 | "Novo Carro: #{super}" 22 | end 23 | end 24 | 25 | carro = Carro.new(:chevrolet, :corsa, :preto, 50) 26 | novo_carro = NovoCarro.new(:volks, :gol, :azul, 42) 27 | 28 | puts carro 29 | puts novo_carro 30 | -------------------------------------------------------------------------------- /classes/carro2.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | def initialize(marca, modelo, cor, tanque) 3 | @marca = marca 4 | @modelo = modelo 5 | @cor = cor 6 | @tanque = tanque 7 | end 8 | 9 | def to_s 10 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 11 | end 12 | end 13 | 14 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 15 | p corsa 16 | puts corsa 17 | -------------------------------------------------------------------------------- /classes/carro3.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | def initialize(marca, modelo, cor, tanque) 3 | @marca = marca 4 | @modelo = modelo 5 | @cor = cor 6 | @tanque = tanque 7 | end 8 | 9 | def to_s 10 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 11 | end 12 | end 13 | 14 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 15 | puts corsa.marca 16 | -------------------------------------------------------------------------------- /classes/carro4.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :cor, :tanque 3 | 4 | def initialize(marca, modelo, cor, tanque) 5 | @marca = marca 6 | @modelo = modelo 7 | @cor = cor 8 | @tanque = tanque 9 | end 10 | 11 | def to_s 12 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 13 | end 14 | end 15 | 16 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 17 | puts corsa.marca 18 | -------------------------------------------------------------------------------- /classes/carro5.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :cor, :tanque 3 | attr_writer :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 14 | end 15 | end 16 | 17 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 18 | corsa.cor = :branco 19 | puts corsa 20 | -------------------------------------------------------------------------------- /classes/carro6.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 14 | end 15 | end 16 | 17 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 18 | corsa.cor = :branco 19 | puts corsa 20 | -------------------------------------------------------------------------------- /classes/carro7.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 14 | end 15 | 16 | def galoes 17 | @tanque / 3.785 18 | end 19 | end 20 | 21 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 22 | corsa.cor = :branco 23 | puts corsa.galoes 24 | -------------------------------------------------------------------------------- /classes/carro8.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 14 | end 15 | end 16 | 17 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 18 | 19 | class Carro 20 | def novo_metodo 21 | puts "Novo método!" 22 | end 23 | end 24 | corsa.novo_metodo 25 | 26 | class Carro 27 | remove_method :novo_metodo 28 | end 29 | 30 | corsa.novo_metodo 31 | -------------------------------------------------------------------------------- /classes/carro9.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 14 | end 15 | end 16 | 17 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 18 | gol = Carro.new(:volks, :gol, :azul, 42) 19 | 20 | Carro.send(:define_method, "multiplica_tanque") do |valor| 21 | @tanque * valor 22 | end 23 | 24 | puts corsa.multiplica_tanque(2) 25 | puts gol.multiplica_tanque(2) 26 | -------------------------------------------------------------------------------- /classes/carro_safe.rb: -------------------------------------------------------------------------------- 1 | class Volante 2 | attr_reader :cor 3 | 4 | def initialize(cor) 5 | @cor = cor 6 | end 7 | end 8 | 9 | class Carro 10 | attr_reader :volante 11 | 12 | def initialize(volante) 13 | @volante = volante 14 | end 15 | end 16 | 17 | volante = Volante.new(:preto) 18 | carro = Carro.new(volante) 19 | 20 | puts carro.volante.cor if carro && carro.volante && carro.volante.cor 21 | #puts carro.try(:volante).try(:cor) 22 | puts carro&.volante&.cor 23 | -------------------------------------------------------------------------------- /classes/classvar1.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | @@qtde = 0 5 | 6 | def initialize(marca, modelo, cor, tanque) 7 | @marca = marca 8 | @modelo = modelo 9 | @cor = cor 10 | @tanque = tanque 11 | @@qtde += 1 12 | end 13 | 14 | def to_s 15 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 16 | end 17 | 18 | def qtde 19 | @@qtde 20 | end 21 | end 22 | 23 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 24 | gol = Carro.new(:volks, :gol, :azul, 42) 25 | ferrari = Carro.new(:ferrari, :viper, :vermelho, 70) 26 | 27 | puts ferrari.qtde 28 | -------------------------------------------------------------------------------- /classes/classvar2.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | @@qtde = 0 5 | 6 | def initialize(marca, modelo, cor, tanque) 7 | @marca = marca 8 | @modelo = modelo 9 | @cor = cor 10 | @tanque = tanque 11 | @@qtde += 1 12 | end 13 | 14 | def to_s 15 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 16 | end 17 | 18 | def self.qtde 19 | @@qtde 20 | end 21 | end 22 | 23 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 24 | gol = Carro.new(:volks, :gol, :azul, 42) 25 | ferrari = Carro.new(:ferrari, :enzo, :vermelho, 70) 26 | puts Carro.qtde 27 | -------------------------------------------------------------------------------- /classes/classvar3.rb: -------------------------------------------------------------------------------- 1 | @@qtde = 10 2 | 3 | class Carro 4 | attr_reader :marca, :modelo, :tanque 5 | attr_accessor :cor 6 | @@qtde = 0 7 | puts self 8 | 9 | def initialize(marca, modelo, cor, tanque) 10 | @marca = marca 11 | @modelo = modelo 12 | @cor = cor 13 | @tanque = tanque 14 | @@qtde += 1 15 | end 16 | 17 | def to_s 18 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 19 | end 20 | 21 | def self.qtde 22 | @@qtde 23 | end 24 | end 25 | 26 | puts self 27 | puts @@qtde 28 | -------------------------------------------------------------------------------- /classes/classvar4.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | class << self 6 | attr_accessor :qtde 7 | end 8 | @qtde = 0 9 | 10 | def initialize(marca, modelo, cor, tanque) 11 | @marca = marca 12 | @modelo = modelo 13 | @cor = cor 14 | @tanque = tanque 15 | self.class.qtde += 1 16 | end 17 | 18 | def to_s 19 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 20 | end 21 | end 22 | 23 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 24 | gol = Carro.new(:volks ,:gol, :azul, 42) 25 | ferrari = Carro.new(:ferrari, :enzo, :vermelho, 70) 26 | puts Carro.qtde 27 | -------------------------------------------------------------------------------- /classes/closures.rb: -------------------------------------------------------------------------------- 1 | def cria_contador(inicial, incremento) 2 | contador = inicial 3 | lambda { contador += incremento } 4 | end 5 | 6 | meu_contador = cria_contador(0, 1) 7 | 8 | puts meu_contador.call 9 | puts meu_contador.call 10 | puts meu_contador.call 11 | -------------------------------------------------------------------------------- /classes/deep.rb: -------------------------------------------------------------------------------- 1 | class A 2 | attr_accessor :outro 3 | 4 | def initialize(outro = nil) 5 | @outro = outro 6 | end 7 | 8 | def show 9 | puts "Estou em #{self.class.name}, #{object_id}" 10 | puts "Outro: #{@outro.object_id}" if !@outro.nil? 11 | end 12 | end 13 | 14 | class B < A 15 | end 16 | 17 | a = A.new 18 | b = B.new(a) 19 | 20 | a.show 21 | b.show 22 | 23 | b2 = Marshal.load(Marshal.dump(b)) 24 | b2.show 25 | -------------------------------------------------------------------------------- /classes/descendants.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | end 3 | 4 | class OutroTeste < Teste 5 | end 6 | 7 | puts "Classes que herdam de Teste:" 8 | p Teste.subclasses 9 | -------------------------------------------------------------------------------- /classes/destrutor.rb: -------------------------------------------------------------------------------- 1 | string = 'Oi, mundo!' 2 | ObjectSpace.define_finalizer(string, ->(id) { puts "Estou terminando o objeto #{id}" }) 3 | -------------------------------------------------------------------------------- /classes/dsl.rb: -------------------------------------------------------------------------------- 1 | # typed: false 2 | # frozen_string_literal: true 3 | 4 | class Veiculo 5 | attr_accessor :cor, :marca, :modelo 6 | 7 | def to_s 8 | "Cor: #{@cor} Marca: #{@marca} Modelo: #{@modelo}" 9 | end 10 | end 11 | 12 | class Carro < Veiculo 13 | end 14 | 15 | class Bike < Veiculo 16 | attr_accessor :cambio 17 | 18 | def to_s 19 | "#{super} Câmbio: #{@cambio}" 20 | end 21 | end 22 | 23 | module Configurador 24 | class << self 25 | attr_accessor :objeto 26 | 27 | def configurar(objeto, &bloco) 28 | self.objeto = objeto 29 | instance_eval(&bloco) 30 | 31 | self.objeto 32 | end 33 | 34 | def method_missing(name, *values) 35 | self.objeto.send("#{name}=", *values) 36 | end 37 | end 38 | end 39 | 40 | # utilizando a DSL daqui para baixo 41 | 42 | carro = Configurador.configurar(Carro.new) do 43 | cor :azul 44 | marca :fiat 45 | modelo :pulse 46 | end 47 | 48 | bike = Configurador.configurar(Bike.new) do 49 | cor :preta 50 | marca :specialized 51 | modelo :rockhopper_pro 52 | cambio :slx 53 | end 54 | 55 | puts carro 56 | puts bike 57 | -------------------------------------------------------------------------------- /classes/dup.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque, :criado 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | @criado = Time.now 11 | end 12 | 13 | def to_s 14 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 15 | end 16 | end 17 | 18 | carro = Carro.new(:chevrolet, :corsa, :preto, 50) 19 | puts carro.criado 20 | sleep 1 21 | 22 | outro_carro = carro.dup 23 | puts outro_carro.criado 24 | -------------------------------------------------------------------------------- /classes/fluent.rb: -------------------------------------------------------------------------------- 1 | class SQL 2 | attr_reader :table, :conditions, :order 3 | 4 | def from(table) 5 | @table = table 6 | self 7 | end 8 | 9 | def where(cond) 10 | @conditions = cond 11 | self 12 | end 13 | 14 | def order(order) 15 | @order = order 16 | self 17 | end 18 | 19 | def to_s 20 | "select * from #{@table} where #{@conditions} order by #{@order}" 21 | end 22 | end 23 | 24 | sql = SQL.new.from("carros").where("marca='Ford'").order("modelo") 25 | puts sql 26 | -------------------------------------------------------------------------------- /classes/forward.rb: -------------------------------------------------------------------------------- 1 | require 'forwardable' 2 | 3 | class Motorista 4 | def coloca_cinto 5 | puts "Colocando cinto ..." 6 | end 7 | end 8 | 9 | class Carro 10 | extend Forwardable 11 | 12 | def initialize 13 | @motorista = Motorista.new 14 | end 15 | 16 | def_delegators :@motorista, :coloca_cinto 17 | end 18 | 19 | carro = Carro.new 20 | carro.coloca_cinto 21 | -------------------------------------------------------------------------------- /classes/ghost.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def method_missing(meth) 3 | puts "Não sei o que fazer com a sua requisição: #{meth}" 4 | end 5 | end 6 | 7 | t = Teste.new 8 | t.teste 9 | -------------------------------------------------------------------------------- /classes/hooksmeth.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def self.method_added(meth) 3 | puts "Adicionado o método #{meth}" 4 | end 5 | 6 | def self.method_removed(meth) 7 | puts "Removido o método #{meth}" 8 | end 9 | end 10 | 11 | t = Teste.new 12 | t.class.send(:define_method,"teste") { puts "teste!" } 13 | t.teste 14 | t.class.send(:remove_method,:teste) 15 | t.teste 16 | -------------------------------------------------------------------------------- /classes/initializecopy.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque, :criado 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | @criado = Time.now 11 | end 12 | 13 | def initialize_copy(original) 14 | puts "criado objeto novo #{self.object_id} duplicado de #{original.object_id}" 15 | @criado = Time.now 16 | end 17 | 18 | def to_s 19 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 20 | end 21 | end 22 | 23 | carro = Carro.new(:chevrolet, :corsa, :preto, 50) 24 | puts carro.criado 25 | puts carro.object_id 26 | sleep 1 27 | 28 | outro_carro = carro.dup 29 | puts outro_carro.criado 30 | puts outro_carro.object_id 31 | -------------------------------------------------------------------------------- /classes/insmethinst.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 14 | end 15 | end 16 | 17 | corsa = Carro.new(:chevrolet, :corsa, :preto, 50) 18 | gol = Carro.new(:volks, :gol, :azul, 42) 19 | 20 | class << corsa 21 | def novo_metodo 22 | puts "Novo método!" 23 | end 24 | end 25 | 26 | corsa.novo_metodo 27 | gol.novo_metodo 28 | -------------------------------------------------------------------------------- /classes/methalias.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | 12 | def to_s 13 | "Marca: #{@marca} Modelo: #{@modelo} Cor: #{@cor} Tanque: #{@tanque}" 14 | end 15 | end 16 | 17 | class Carro 18 | alias to_s_old to_s 19 | 20 | def to_s 21 | "Esse é um novo jeito de mostrar isso: #{to_s_old}" 22 | end 23 | end 24 | 25 | carro = Carro.new(:chevrolet, :corsa, :preto, 50) 26 | puts carro 27 | puts carro.to_s_old 28 | -------------------------------------------------------------------------------- /classes/methmissing.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def method_missing(meth, value = nil) 3 | sanitized = meth.to_s.split("=").first 4 | 5 | if meth =~ /=$/ 6 | self.class.send(:define_method, meth) { |it| instance_variable_set("@#{sanitized}", it) } 7 | self.send(meth, value) 8 | else 9 | self.class.send(:define_method, sanitized) { instance_variable_get("@#{sanitized}") } 10 | self.send(meth) 11 | end 12 | end 13 | end 14 | 15 | t = Teste.new 16 | t.oi = "oi, mundo!" 17 | puts t.oi 18 | 19 | puts t.hello 20 | t.hello = "hello, world!" 21 | puts t.hello 22 | -------------------------------------------------------------------------------- /classes/method_missing.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def method_missing(method_name, value = nil) 3 | sanitized = method_name.to_s.split("=").first 4 | 5 | if method_name =~ /=$/ 6 | self.class.send(:define_method, method_name) { |val| instance_variable_set("@#{sanitized}", val) } 7 | self.send(method_name, value) 8 | else 9 | self.class.send(:define_method, sanitized) { instance_variable_get("@#{sanitized}") } 10 | self.send(method_name) 11 | end 12 | end 13 | end 14 | 15 | t = Teste.new 16 | t.oi = "oi, mundo!" 17 | puts t.oi 18 | 19 | puts t.hello 20 | t.hello = "hello, world!" 21 | puts t.hello 22 | -------------------------------------------------------------------------------- /classes/pcm2_static.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | private_class_method def self.desc 3 | puts 'Isso é uma caixa de parafusos' 4 | end 5 | end 6 | 7 | CaixaDeParafusos.desc 8 | -------------------------------------------------------------------------------- /classes/pcm_static.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | def self.desc 3 | puts 'Isso é uma caixa de parafusos' 4 | end 5 | 6 | private_class_method :desc 7 | end 8 | 9 | CaixaDeParafusos.desc 10 | -------------------------------------------------------------------------------- /classes/self_static.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | class << self 3 | private 4 | 5 | def desc 6 | puts 'Isso é uma caixa de parafusos' 7 | end 8 | end 9 | end 10 | 11 | CaixaDeParafusos.desc 12 | -------------------------------------------------------------------------------- /classes/shallow.rb: -------------------------------------------------------------------------------- 1 | class A 2 | attr_reader :outro 3 | 4 | def initialize(outro = nil) 5 | @outro = outro 6 | end 7 | 8 | def show 9 | puts "Estou em #{self.class.name}, #{object_id}" 10 | puts "Outro: #{@outro.object_id}" if !@outro.nil? 11 | end 12 | end 13 | 14 | class B < A 15 | end 16 | 17 | a = A.new 18 | b = B.new(a) 19 | 20 | a.show 21 | b.show 22 | 23 | b2 = b.dup 24 | b2.show 25 | -------------------------------------------------------------------------------- /classes/subclasses.rb: -------------------------------------------------------------------------------- 1 | class Automovel 2 | end 3 | 4 | class Carro < Automovel 5 | end 6 | 7 | class Van < Automovel 8 | end 9 | 10 | class Onibus < Automovel 11 | end 12 | 13 | p Automovel.subclasses 14 | -------------------------------------------------------------------------------- /classes/superclasses.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | end 3 | 4 | class OutroTeste < Teste 5 | end 6 | 7 | p String.superclass 8 | p Teste.superclass 9 | p OutroTeste.superclass 10 | -------------------------------------------------------------------------------- /classes/supermeth.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def metodo(parametro1) 3 | puts parametro1 4 | end 5 | end 6 | 7 | class NovoTeste < Teste 8 | def metodo(parametro1, parametro2) 9 | super(parametro1) 10 | puts parametro2 11 | end 12 | end 13 | 14 | t1 = Teste.new 15 | t2 = NovoTeste.new 16 | t1.metodo(1) 17 | t2.metodo(2,3) 18 | -------------------------------------------------------------------------------- /classes/wrong_static.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | private 3 | 4 | def self.desc 5 | puts 'Isso é uma caixa de parafusos' 6 | end 7 | end 8 | 9 | CaixaDeParafusos.desc 10 | -------------------------------------------------------------------------------- /database/alunos: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/database/alunos -------------------------------------------------------------------------------- /database/alunos.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/database/alunos.sqlite3 -------------------------------------------------------------------------------- /database/db1.rb: -------------------------------------------------------------------------------- 1 | require 'sequel' 2 | 3 | Sequel.sqlite(database: 'alunos.sqlite3') do |con| 4 | con.run('drop table if exists alunos') 5 | 6 | sql = < 2 | 3 | 4 | 5 | 6 | 7 | RDoc Documentation 8 | 9 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 71 | 72 |
73 |

This is the API documentation for RDoc Documentation. 74 |

75 | 76 | 77 | 82 | 83 | -------------------------------------------------------------------------------- /docs/rdoc/doc/js/darkfish.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Darkfish Page Functions 4 | * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ 5 | * 6 | * Author: Michael Granger 7 | * 8 | */ 9 | 10 | /* Provide console simulation for firebug-less environments */ 11 | /* 12 | if (!("console" in window) || !("firebug" in console)) { 13 | var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", 14 | "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; 15 | 16 | window.console = {}; 17 | for (var i = 0; i < names.length; ++i) 18 | window.console[names[i]] = function() {}; 19 | }; 20 | */ 21 | 22 | 23 | function showSource( e ) { 24 | var target = e.target; 25 | while (!target.classList.contains('method-detail')) { 26 | target = target.parentNode; 27 | } 28 | if (typeof target !== "undefined" && target !== null) { 29 | target = target.querySelector('.method-source-code'); 30 | } 31 | if (typeof target !== "undefined" && target !== null) { 32 | target.classList.toggle('active-menu') 33 | } 34 | }; 35 | 36 | function hookSourceViews() { 37 | document.querySelectorAll('.method-heading').forEach(function (codeObject) { 38 | codeObject.addEventListener('click', showSource); 39 | }); 40 | }; 41 | 42 | function hookSearch() { 43 | var input = document.querySelector('#search-field'); 44 | var result = document.querySelector('#search-results'); 45 | result.classList.remove("initially-hidden"); 46 | 47 | var search_section = document.querySelector('#search-section'); 48 | search_section.classList.remove("initially-hidden"); 49 | 50 | var search = new Search(search_data, input, result); 51 | 52 | search.renderItem = function(result) { 53 | var li = document.createElement('li'); 54 | var html = ''; 55 | 56 | // TODO add relative path to 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 |

Table of Contents - RDoc Documentation

27 | 28 | 29 |

Classes and Modules

30 | 43 | 44 |

Methods

45 |
    46 | 47 |
  • 48 | ::new 49 | — 50 | Carro 51 | 52 |
  • 53 | #ipva 54 | — 55 | Fusca 56 | 57 |
  • 58 | #to_s 59 | — 60 | Carro 61 |
62 |
63 | 64 | 65 | 70 | 71 | -------------------------------------------------------------------------------- /docs/yard/.yardoc/checksums: -------------------------------------------------------------------------------- 1 | carro.rb 299391ac5703f8c36946317df2be8ad67e1def73 2 | carro_complete.rb 2673b4a7fb9bd398f55a4ef8349ae9f4681268f6 3 | -------------------------------------------------------------------------------- /docs/yard/.yardoc/complete: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/docs/yard/.yardoc/complete -------------------------------------------------------------------------------- /docs/yard/.yardoc/object_types: -------------------------------------------------------------------------------- 1 | {: root[;: 2 | class[I" 3 | Carro:EFI" 4 | Fusca;F: method[ I"Carro#marca;FI"Carro#modelo;FI"Carro#tanque;FI"Carro#cor;FI"Carro#cor=;FI"Carro#initialize;FI"Carro#to_s;FI"Fusca#ipva;F -------------------------------------------------------------------------------- /docs/yard/.yardoc/objects/root.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/docs/yard/.yardoc/objects/root.dat -------------------------------------------------------------------------------- /docs/yard/.yardoc/proxy_types: -------------------------------------------------------------------------------- 1 | { -------------------------------------------------------------------------------- /docs/yard/carro.rb: -------------------------------------------------------------------------------- 1 | # Essa é a classe base para todos os carros que vamos 2 | # criar no nosso programa. A partir dela criamos carros 3 | # de marcas específicas. 4 | # 5 | # Autor:: Eustáquio 'TaQ' Rangel 6 | # Licença:: GPL 7 | class Carro 8 | attr_reader :marca, :modelo, :tanque 9 | attr_accessor :cor 10 | 11 | # Parâmetros obrigatórios para criar o carro 12 | # Não se esqueça de que todo carro vai ter os custos de: 13 | # * IPVA 14 | # * Seguro obrigatório 15 | # * Seguro 16 | # * Manutenção 17 | def initialize(marca,modelo,cor,tanque) 18 | @marca = marca 19 | @modelo = modelo 20 | @cor = cor 21 | @tanque = tanque 22 | end 23 | 24 | # Converte o carro em uma representação mais legível 25 | def to_s 26 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /docs/yard/carro_complete.rb: -------------------------------------------------------------------------------- 1 | # = Classe 2 | # Essa é a classe base para *todos* os carros que vamos 3 | # criar no nosso programa. A partir dela criamos carros 4 | # de _marcas_ específicas. Verique o método to_s dessa 5 | # classe Carro para uma descrição mais legível. 6 | # 7 | # @author Eustáquio Rangel 8 | # 9 | # Parâmetros obrigatórios para criar o carro 10 | # Não se esqueça de que todo carro vai ter os custos de: 11 | # * IPVA 12 | # * Seguro obrigatório 13 | # * Seguro 14 | # * Manutenção 15 | # 16 | # @!attribute [r] marca 17 | # @return [Symbol] retorna a marca do carro 18 | # 19 | # @!attribute [r] modelo 20 | # @return [Symbol] retorna o modelo do carro 21 | # 22 | # @!attribute [r] tanque 23 | # @return [Integer] retorna a capacidade do tanque do carro, em litros 24 | # 25 | # @!attribute [rw] cor 26 | # @return [Symbol] atribui e retorna a cor do carro 27 | # 28 | class Carro 29 | attr_reader :marca, :modelo, :tanque 30 | attr_accessor :cor 31 | 32 | # @param marca [Symbol] a marca do carro 33 | # @param modelo [Symbol] o modelo do carro 34 | # @param cor [Symbol] a cor do carro 35 | # @param tanque [Integer] a capacidade, em litros, do tanque do carro 36 | # 37 | # @return um novo objeto da classe Carro 38 | def initialize(marca, modelo, cor, tanque) 39 | @marca = marca 40 | @modelo = modelo 41 | @cor = cor 42 | @tanque = tanque 43 | end 44 | 45 | # Converte o carro em uma representação mais legível 46 | def to_s 47 | "Marca:#{@marca} Modelo:#{@modelo} Cor:#{@cor} Tanque:#{@tanque}" 48 | end 49 | end 50 | 51 | # Classe de um _vokinho_, derivada da classe Carro. 52 | class Fusca < Carro 53 | # @return [Boolean] se paga IPVA esse ano 54 | def ipva 55 | false 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /docs/yard/doc/_index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Documentation by YARD 0.9.34 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 32 | 33 |
34 | 54 | 55 |

Documentation by YARD 0.9.34

56 |
57 |

Alphabetic Index

58 | 59 |
60 |

Namespace Listing A-Z

61 | 62 | 63 | 64 | 65 | 66 | 67 | 96 | 97 |
68 | 69 | 70 |
    71 |
  • C
  • 72 |
      73 | 74 |
    • 75 | Carro 76 | 77 |
    • 78 | 79 |
    80 |
81 | 82 | 83 |
    84 |
  • F
  • 85 |
      86 | 87 |
    • 88 | Fusca 89 | 90 |
    • 91 | 92 |
    93 |
94 | 95 |
98 | 99 |
100 | 101 |
102 | 103 | 108 | 109 |
110 | 111 | -------------------------------------------------------------------------------- /docs/yard/doc/class_list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Class List 19 | 20 | 21 | 22 |
23 |
24 |

Class List

25 |
26 | 27 | 28 | Classes 29 | 30 | 31 | 32 | Methods 33 | 34 | 35 | 36 | Files 37 | 38 | 39 |
40 | 41 | 42 |
43 | 44 | 49 |
50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/yard/doc/css/common.css: -------------------------------------------------------------------------------- 1 | /* Override this file with custom rules */ -------------------------------------------------------------------------------- /docs/yard/doc/file_list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | File List 19 | 20 | 21 | 22 |
23 |
24 |

File List

25 |
26 | 27 | 28 | Classes 29 | 30 | 31 | 32 | Methods 33 | 34 | 35 | 36 | Files 37 | 38 | 39 |
40 | 41 | 42 |
43 | 44 |
    45 | 46 | 47 | 48 |
49 |
50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/yard/doc/frames.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Documentation by YARD 0.9.34 6 | 7 | 13 | 17 | 18 | -------------------------------------------------------------------------------- /docs/yard/doc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Documentation by YARD 0.9.34 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 32 | 33 |
34 | 54 | 55 |

Documentation by YARD 0.9.34

56 |
57 |

Alphabetic Index

58 | 59 |
60 |

Namespace Listing A-Z

61 | 62 | 63 | 64 | 65 | 66 | 67 | 96 | 97 |
68 | 69 | 70 |
    71 |
  • C
  • 72 |
      73 | 74 |
    • 75 | Carro 76 | 77 |
    • 78 | 79 |
    80 |
81 | 82 | 83 |
    84 |
  • F
  • 85 |
      86 | 87 |
    • 88 | Fusca 89 | 90 |
    • 91 | 92 |
    93 |
94 | 95 |
98 | 99 |
100 | 101 |
102 | 103 | 108 | 109 |
110 | 111 | -------------------------------------------------------------------------------- /docs/yard/doc/method_list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Method List 19 | 20 | 21 | 22 |
23 |
24 |

Method List

25 |
26 | 27 | 28 | Classes 29 | 30 | 31 | 32 | Methods 33 | 34 | 35 | 36 | Files 37 | 38 | 39 |
40 | 41 | 42 |
43 | 44 |
    45 | 46 | 47 |
  • 48 |
    49 | #cor 50 | Carro 51 |
    52 |
  • 53 | 54 | 55 |
  • 56 |
    57 | #initialize 58 | Carro 59 |
    60 |
  • 61 | 62 | 63 |
  • 64 |
    65 | #ipva 66 | Fusca 67 |
    68 |
  • 69 | 70 | 71 |
  • 72 |
    73 | #marca 74 | Carro 75 |
    76 |
  • 77 | 78 | 79 |
  • 80 |
    81 | #modelo 82 | Carro 83 |
    84 |
  • 85 | 86 | 87 |
  • 88 |
    89 | #tanque 90 | Carro 91 |
    92 |
  • 93 | 94 | 95 |
  • 96 |
    97 | #to_s 98 | Carro 99 |
    100 |
  • 101 | 102 | 103 | 104 |
105 |
106 | 107 | 108 | -------------------------------------------------------------------------------- /docs/yard/doc/top-level-namespace.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Top Level Namespace 8 | 9 | — Documentation by YARD 0.9.34 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 34 | 35 |
36 | 61 | 62 |

Top Level Namespace 63 | 64 | 65 | 66 |

67 |
68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 |
80 | 81 |

Defined Under Namespace

82 |

83 | 84 | 85 | 86 | 87 | Classes: Carro, Fusca 88 | 89 | 90 |

91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 |
101 | 102 | 107 | 108 |
109 | 110 | -------------------------------------------------------------------------------- /gc/gc1.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | end 3 | 4 | t1 = Teste.new 5 | t2 = Teste.new 6 | t3 = Teste.new 7 | 8 | count = ObjectSpace.each_object(Teste) do |object| 9 | puts object 10 | end 11 | puts "#{count} objetos encontrados." 12 | 13 | t2 = nil 14 | GC.start 15 | 16 | count = ObjectSpace.each_object(Teste) do |object| 17 | puts object 18 | end 19 | puts "#{count} objetos encontrados." 20 | -------------------------------------------------------------------------------- /gc/gc2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | char str[15] = "hello world"; 5 | printf("%s\n", str); 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /gc/gc2.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | end 3 | 4 | t1 = Teste.new 5 | t2 = Teste.new 6 | t3 = Teste.new 7 | 8 | count = ObjectSpace.each_object(Teste) do |object| 9 | puts object 10 | end 11 | puts "#{count} objetos encontrados." 12 | 13 | t2 = nil 14 | 15 | puts "Antes:" 16 | p GC.stat 17 | 18 | GC.start 19 | 20 | puts "Depois:" 21 | p GC.stat 22 | 23 | count = ObjectSpace.each_object(Teste) do |object| 24 | puts object 25 | end 26 | puts "#{count} objetos encontrados." 27 | -------------------------------------------------------------------------------- /gc/gc3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/gc/gc3 -------------------------------------------------------------------------------- /gc/gc3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int size = ((int) ((sizeof(void *) * 3) / sizeof(char) - 1)); 6 | printf("%d bits: %d bytes de comprimento\n", __WORDSIZE, size); 7 | } 8 | -------------------------------------------------------------------------------- /gc/gc4.c: -------------------------------------------------------------------------------- 1 | struct RString { 2 | 3 | struct RBasic basic; 4 | 5 | union { 6 | struct { 7 | long len; 8 | char *ptr; 9 | union { 10 | long capa; 11 | VALUE shared; 12 | } aux; 13 | } heap; 14 | 15 | char ary[RSTRING_EMBED_LEN_MAX + 1]; 16 | } as; 17 | }; 18 | -------------------------------------------------------------------------------- /gc/gc5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/gc/gc5 -------------------------------------------------------------------------------- /gc/gc5.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | union data { 6 | int id; 7 | char name[20]; 8 | }; 9 | 10 | int main() { 11 | union data d; 12 | d.id = 1; 13 | strcpy(d.name, "taq"); 14 | printf("%d %s\n", d.id, d.name); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /gc/gc6: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/gc/gc6 -------------------------------------------------------------------------------- /gc/gc6.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | union data { 6 | int id; 7 | char name[20]; 8 | }; 9 | 10 | int main() { 11 | union data d; 12 | 13 | d.id = 1; 14 | printf("%d\n", d.id); 15 | 16 | strcpy(d.name, "taq"); 17 | printf("%s\n", d.name); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /gc/null: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/gc/null -------------------------------------------------------------------------------- /gc/null.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | char *str; 7 | str = malloc(sizeof(char) * 15); 8 | strcpy(str, "hello world"); 9 | printf("%s\n", str); 10 | free(str); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /gc/str_bench.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | 3 | Benchmark.bm do |bm| 4 | bm.report('alocando strings com menos de 23 caracteres') do 5 | 1_000_000.times { s = '*' * 10 } 6 | end 7 | 8 | bm.report('alocando strings com 23 caracteres') do 9 | 1_000_000.times { s = '*' * 23 } 10 | end 11 | 12 | bm.report('alocando strings com 24 caracteres') do 13 | 1_000_000.times { s = '*' * 24 } 14 | end 15 | 16 | bm.report('alocando strings com mais de 24 caracteres') do 17 | 1_000_000.times { s = '*' * 100 } 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /gc/sym_gc.rb: -------------------------------------------------------------------------------- 1 | puts Symbol.all_symbols.size 2 | 3 | 100_000.times do |i| 4 | "sym#{i}".to_sym 5 | end 6 | 7 | puts Symbol.all_symbols.size 8 | GC.start 9 | 10 | puts Symbol.all_symbols.size 11 | -------------------------------------------------------------------------------- /gems/Fib.java: -------------------------------------------------------------------------------- 1 | public class Fib { 2 | public static long calcula(int numero) { 3 | if (numero < 2) { 4 | return numero; 5 | } 6 | return calcula(numero - 1) + calcula(numero - 2); 7 | } 8 | 9 | public static void main(String args[]) { 10 | long started_at = System.currentTimeMillis(); 11 | System.out.println(calcula(Integer.parseInt(args[0]))); 12 | 13 | long diff = System.currentTimeMillis() - started_at; 14 | System.out.println((float) diff / 1000); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /gems/load2.rb: -------------------------------------------------------------------------------- 1 | class Teste 2 | def initialize 3 | puts "comportamento reescrito" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /gems/memo.cache: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/gems/memo.cache -------------------------------------------------------------------------------- /gems/memo1.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | 3 | def fib(numero) 4 | return numero if numero < 2 5 | fib(numero - 1) + fib(numero - 2) 6 | end 7 | 8 | puts Benchmark.measure { puts fib(ARGV[0].to_i) } 9 | -------------------------------------------------------------------------------- /gems/memo2.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | require 'memoize' 3 | include Memoize 4 | 5 | def fib(numero) 6 | return numero if numero < 2 7 | fib(numero - 1) + fib(numero - 2) 8 | end 9 | memoize(:fib) 10 | 11 | puts Benchmark.measure { puts fib(ARGV[0].to_i) } 12 | -------------------------------------------------------------------------------- /gems/memo3.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | require 'memoize' 3 | include Memoize 4 | 5 | def fib(numero) 6 | return numero if numero < 2 7 | fib(numero - 1) + fib(numero - 2) 8 | end 9 | memoize(:fib, 'memo.cache') 10 | 11 | puts Benchmark.measure { puts fib(ARGV[0].to_i) } 12 | -------------------------------------------------------------------------------- /gems/portnum/.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | -------------------------------------------------------------------------------- /gems/portnum/Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source "https://rubygems.org" 4 | 5 | # Specify your gem's dependencies in portnum.gemspec 6 | gemspec 7 | 8 | gem "rake", "~> 13.0" 9 | 10 | gem "minitest", "~> 5.0" 11 | -------------------------------------------------------------------------------- /gems/portnum/README.md: -------------------------------------------------------------------------------- 1 | # Portnum 2 | 3 | Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/portnum`. To experiment with that code, run `bin/console` for an interactive prompt. 4 | 5 | TODO: Delete this and the text above, and describe your gem 6 | 7 | ## Installation 8 | 9 | Add this line to your application's Gemfile: 10 | 11 | ```ruby 12 | gem 'portnum' 13 | ``` 14 | 15 | And then execute: 16 | 17 | $ bundle install 18 | 19 | Or install it yourself as: 20 | 21 | $ gem install portnum 22 | 23 | ## Usage 24 | 25 | TODO: Write usage instructions here 26 | 27 | ## Development 28 | 29 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 30 | 31 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). 32 | 33 | ## Contributing 34 | 35 | Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/portnum. 36 | -------------------------------------------------------------------------------- /gems/portnum/Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "bundler/gem_tasks" 4 | require "rake/testtask" 5 | 6 | Rake::TestTask.new(:test) do |t| 7 | t.libs << "test" 8 | t.libs << "lib" 9 | t.test_files = FileList["test/**/*_test.rb"] 10 | end 11 | 12 | task default: :test 13 | -------------------------------------------------------------------------------- /gems/portnum/bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "bundler/setup" 5 | require "portnum" 6 | 7 | # You can add fixtures and/or initialization code here to make experimenting 8 | # with your gem easier. You can also use a different console, if you like. 9 | 10 | # (If you use this, don't forget to add pry to your Gemfile!) 11 | # require "pry" 12 | # Pry.start 13 | 14 | require "irb" 15 | IRB.start(__FILE__) 16 | -------------------------------------------------------------------------------- /gems/portnum/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /gems/portnum/lib/portnum.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "portnum/version" 4 | 5 | class Numeric 6 | def par? 7 | self % 2 == 0 8 | end 9 | 10 | def impar? 11 | self % 2 != 0 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /gems/portnum/lib/portnum/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Portnum 4 | VERSION = "0.1.0" 5 | end 6 | -------------------------------------------------------------------------------- /gems/portnum/portnum.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "lib/portnum/version" 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = "portnum" 7 | spec.version = Portnum::VERSION 8 | spec.authors = ["Eustaquio Rangel"] 9 | spec.email = ["taq@eustaquiorangel.com"] 10 | 11 | spec.summary = "Aportuguesamento de números" 12 | spec.description = "Adiciona os métodos par? e impar? na classe Numeric" 13 | spec.homepage = "http://github.com/taq/portnum" 14 | spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") 15 | 16 | spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" 17 | 18 | spec.metadata["homepage_uri"] = spec.homepage 19 | spec.metadata["source_code_uri"] = "http://github.com/taq/portnum" 20 | spec.metadata["changelog_uri"] = "http://github.com/taq/portnum/CHANGELOG.md" 21 | 22 | # Specify which files should be added to the gem when it is released. 23 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 24 | spec.files = Dir.chdir(File.expand_path(__dir__)) do 25 | `git ls-files -z`.split("\x0").reject { |it| it.match(%r{\A(?:test|spec|features)/}) } 26 | end 27 | spec.bindir = "exe" 28 | spec.executables = spec.files.grep(%r{\Aexe/}) { |it| File.basename(it) } 29 | spec.require_paths = ["lib"] 30 | 31 | # Uncomment to register a new dependency of your gem 32 | # spec.add_dependency "example-gem", "~> 1.0" 33 | 34 | # For more information and examples about making a new gem, checkout our 35 | # guide at: https://bundler.io/guides/creating_gem.html 36 | end 37 | -------------------------------------------------------------------------------- /gems/portnum/test/portnum_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test_helper" 4 | 5 | class PortnumTest < Minitest::Test 6 | def test_that_it_has_a_version_number 7 | refute_nil ::Portnum::VERSION 8 | end 9 | 10 | def test_par 11 | assert_respond_to 1, :par? 12 | end 13 | 14 | def test_par_ok 15 | assert 2.par? 16 | assert !1.par? 17 | end 18 | 19 | def test_impar 20 | assert_respond_to 1, :impar? 21 | end 22 | 23 | def test_impar_ok 24 | assert 1.impar? 25 | assert !2.impar? 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /gems/portnum/test/test_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | $LOAD_PATH.unshift File.expand_path("../lib", __dir__) 4 | require "portnum" 5 | 6 | require "minitest/autorun" 7 | -------------------------------------------------------------------------------- /gems/tco1.rb: -------------------------------------------------------------------------------- 1 | def fact(n) 2 | return 1 if n <= 1 3 | 4 | n * fact(n-1) 5 | end 6 | 7 | [4, 40_000].each do |num| 8 | puts fact(num) 9 | end 10 | -------------------------------------------------------------------------------- /gems/tco2.rb: -------------------------------------------------------------------------------- 1 | def fact(n, ac = 1) 2 | return ac if n <= 1 3 | 4 | fact(n - 1, n * ac) 5 | end 6 | 7 | [4, 40_000].each do |num| 8 | puts fact(num) 9 | end 10 | -------------------------------------------------------------------------------- /gems/tco3.rb: -------------------------------------------------------------------------------- 1 | RubyVM::InstructionSequence.compile_option = { 2 | tailcall_optimization: true, 3 | trace_instruction: false 4 | } 5 | 6 | require_relative 'tco2.rb' 7 | 8 | [4, 40_000].each do |num| 9 | puts fact(num) 10 | end 11 | -------------------------------------------------------------------------------- /io/1.txt: -------------------------------------------------------------------------------- 1 | 111 2 | -------------------------------------------------------------------------------- /io/2.txt: -------------------------------------------------------------------------------- 1 | 222 2 | -------------------------------------------------------------------------------- /io/3.txt: -------------------------------------------------------------------------------- 1 | 333 2 | -------------------------------------------------------------------------------- /io/README: -------------------------------------------------------------------------------- 1 | This is ftp.gnu.org, the FTP server of the the GNU project. 2 | 3 | NOTICE (Updated October 13 2017): 4 | 5 | Because of security concerns with plaintext protocols, we still 6 | intend to disable the FTP protocol for downloads on this server 7 | (downloads would still be available over HTTP and HTTPS), but we 8 | will not be doing it on November 1, 2017, as previously announced 9 | here. We will be sharing our reasons and offering a chance to 10 | comment on this issue soon; watch this space for details. 11 | 12 | If you maintain scripts used to access ftp.gnu.org over FTP, 13 | we strongly encourage you to change them to use HTTPS instead. 14 | 15 | --- 16 | 17 | Comments, suggestions, problems and complaints should be reported via 18 | email to 'gnu@gnu.org'. 19 | 20 | gnu/ Contains GNU programs and documents that we develop for the GNU 21 | system (or pointers on where to get the programs, if we don't 22 | keep the files here). These are programs that fit the 23 | definition of GNU software at: 24 | http://www.gnu.org/philosophy/categories.html#GNUsoftware 25 | 26 | old-gnu/ Older versions of GNU software. 27 | 28 | non-gnu/ We distribute some non-GNU programs through our FTP server, or 29 | provide pointers to where they are. We put these 30 | programs/pointers in this directory since they are not 31 | developed by the GNU project. They are, of course, part of 32 | the GNU system. See: 33 | http://www.gnu.org/philosophy/categories.html#TheGNUsystem 34 | 35 | third-party Contains GNU software that has been modified by third 36 | parties. We don't necessarily know the specifics of 37 | what these modifications do or how these modified versions 38 | work. We provide this directory as a service to GNU users 39 | who might find these modifications useful. 40 | 41 | iso Contains bootable CD images (ISO9660) of a development 42 | snapshot of the Debian GNU/Hurd complete operating system. 43 | 44 | ls-lrR.txt.gz The output of `ls -lrR' run from this directory. This can 45 | be used to see what files are here. This is a gzip'ed version of the file. 46 | 47 | find.txt.gz The output of `find .' run from this directory. This can 48 | be used to see what files are here. This is a gzip'ed version of the file. 49 | 50 | tree.json.gz The output of `tree -aJsD --timefmt %s' run from this directory 51 | each time it changes. This can be used to see what files are here. The 52 | timestamp of this file can be used to see if has been any change to the 53 | ftp, and the timestamp of any file to know if it has not changed. This is 54 | a gzip'ed version of the file. 55 | 56 | lpf.README A description of where to find information on the League for 57 | Programming Freedom, since this information is not kept here 58 | anymore. 59 | 60 | There are also .sig files, which contain detached GPG signatures of the above 61 | files, automatically signed by the same script that generates them. 62 | 63 | You can verify the signatures for gnu project files with the keyring file from: 64 | https://ftp.gnu.org/gnu/gnu-keyring.gpg 65 | 66 | In a directory with the keyring file, the source file to verify and the 67 | signature file, the command to use is: 68 | 69 | $ gpg --verify --keyring ./gnu-keyring.gpg foo.tar.xz.sig 70 | 71 | 72 | -------------------------------------------------------------------------------- /io/RPCClient.java: -------------------------------------------------------------------------------- 1 | import java.net.URL; 2 | import java.util.Vector; 3 | import java.util.HashMap; 4 | import org.apache.xmlrpc.common.*; 5 | import org.apache.xmlrpc.client.*; 6 | 7 | public class RPCClient { 8 | public static void main(String args[]) { 9 | try { 10 | Vector params; 11 | XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); 12 | config.setServerURL(new URL("http://localhost:8081/RPC2")); 13 | XmlRpcClient server = new XmlRpcClient(); 14 | server.setConfig(config); 15 | 16 | params = new Vector(); 17 | params.addElement(new Integer(5)); 18 | params.addElement(new Integer(3)); 19 | 20 | HashMap result = (HashMap) server.execute("soma", params); 21 | int sum = ((Integer) result.get("resultado")).intValue(); 22 | System.out.println("O resultado da soma é " + Integer.toString(sum)); 23 | 24 | params = new Vector(); 25 | params.addElement(new Integer(11)); 26 | params.addElement(new Integer(4)); 27 | result = (HashMap) server.execute("divide", params); 28 | 29 | int divide = ((Integer) result.get("resultado")).intValue(); 30 | int resto = ((Integer) result.get("resto")).intValue(); 31 | System.out.println("O resultado da divisão é " + Integer.toString(sum) + " e o resto é: " + Integer.toString(resto)); 32 | } catch(Exception error) { 33 | System.err.println("erro:" + error.getMessage()); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /io/alunos.html: -------------------------------------------------------------------------------- 1 | Teste de XSLT 2 | 3 | 4 | 5 | 6 |
Alunos
IdNome
1João
2José
3Antonio
4Maria
7 | -------------------------------------------------------------------------------- /io/alunos.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1 5 | João 6 | 7 | 8 | 2 9 | José 10 | 11 | 12 | 3 13 | Antonio 14 | 15 | 16 | 4 17 | Maria 18 | 19 | 20 | -------------------------------------------------------------------------------- /io/alunos.xsl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Teste de XSLT 8 | 9 | 10 | 11 | 12 | 13 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Alunos
14 | IdNome
22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |
33 | -------------------------------------------------------------------------------- /io/bytes.rb: -------------------------------------------------------------------------------- 1 | File.open("teste.txt") do |arquivo| 2 | arquivo.each_byte do |byte| 3 | print "[#{byte}]" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /io/chars.rb: -------------------------------------------------------------------------------- 1 | File.open("teste.txt") do |arquivo| 2 | arquivo.each_char do |char| 3 | print "[#{char}]" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /io/copy.rb: -------------------------------------------------------------------------------- 1 | File.open("novo_teste.txt","w") do |arquivo| 2 | arquivo << File.read("teste.txt") 3 | end 4 | -------------------------------------------------------------------------------- /io/csv_read1.rb: -------------------------------------------------------------------------------- 1 | require 'csv' 2 | 3 | file = 'colors.csv' 4 | colors = CSV.parse(File.read(file)) 5 | 6 | p colors 7 | -------------------------------------------------------------------------------- /io/csv_read2.rb: -------------------------------------------------------------------------------- 1 | require 'csv' 2 | 3 | file = 'colors.csv' 4 | 5 | CSV.parse(File.read(file), headers: true).each do |row| 6 | puts "o código da cor #{row['color']} é #{row['hex']}" 7 | end 8 | -------------------------------------------------------------------------------- /io/csv_read3.rb: -------------------------------------------------------------------------------- 1 | require 'csv' 2 | require 'benchmark' 3 | 4 | file = ARGV[0] 5 | puts "Processando arquivo #{file} ..." 6 | 7 | Benchmark.bm do |bm| 8 | bm.report 'parse' do 9 | CSV.parse(File.read(file)) 10 | end 11 | bm.report 'foreach' do 12 | CSV.foreach(file) do |row| 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /io/csv_types.csv: -------------------------------------------------------------------------------- 1 | 1,1.2,1.23,2024-12-27,2024-12-27 12:17,symbol 2 | -------------------------------------------------------------------------------- /io/csv_write.rb: -------------------------------------------------------------------------------- 1 | require 'csv' 2 | 3 | header = %w[color hex] 4 | data = [ 5 | [:red, '#ff0000'], 6 | [:green, '#00ff00'], 7 | [:blue, '#0000ff'] 8 | ] 9 | file = 'colors.csv' 10 | 11 | CSV.open(file, 'w') do |csv| 12 | csv << header 13 | data.each do |row| 14 | csv << row 15 | end 16 | end 17 | 18 | puts File.read(file) 19 | -------------------------------------------------------------------------------- /io/data.rb: -------------------------------------------------------------------------------- 1 | DATA.each do |linha| 2 | puts "linha: #{linha}" 3 | end 4 | 5 | __END__ 6 | Esse é um teste 7 | de dados 8 | embutidos no arquivo 9 | de código-fonte 10 | -------------------------------------------------------------------------------- /io/faraday.rb: -------------------------------------------------------------------------------- 1 | require 'faraday' 2 | 3 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 4 | query = URI.encode_www_form(params) 5 | headers = { 6 | 'Content-Type': 'application/json', 7 | 'Authorization': 'Bearer ' 8 | } 9 | 10 | host = Faraday.new(url: 'http://localhost:2000') 11 | host.get('/', params, headers) 12 | host.post('/', params.to_json, headers) 13 | -------------------------------------------------------------------------------- /io/flip_flop.rb: -------------------------------------------------------------------------------- 1 | File.open('flip_flop_test.txt').each do |line| 2 | if line.match?(/^\_start_/) .. line.match?(/^_end_/) 3 | puts "\t#{line}".gsub(/_\w+_/, '') 4 | else 5 | puts line 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /io/flip_flop_test.txt: -------------------------------------------------------------------------------- 1 | _start_ 2 | Esse é um parágrafo de texto 3 | que vai ser indentado. 4 | _end_ 5 | esse não vai ter indentação. 6 | esse também não. 7 | _start_ 8 | E aqui tem outro! 9 | _end_ 10 | _start_ 11 | E mais um aqui 12 | com mais linhas 13 | só de teste. 14 | _end_ 15 | -------------------------------------------------------------------------------- /io/ftp.rb: -------------------------------------------------------------------------------- 1 | require "net/ftp" 2 | 3 | host = "ftp.gnu.org" 4 | user = "anonymous" 5 | pass = "eustaquiorangel@gmail.com" 6 | file = "README" 7 | 8 | begin 9 | Net::FTP.open(host) do |ftp| 10 | puts "Conexão FTP aberta." 11 | ftp.login(user, pass) 12 | 13 | puts "Requisitando arquivo ..." 14 | ftp.chdir("pub") 15 | ftp.get(file) 16 | puts "Download efetuado." 17 | 18 | puts File.read(file) 19 | end 20 | rescue => exception 21 | puts "ERRO: #{exception}" 22 | end 23 | -------------------------------------------------------------------------------- /io/http1.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | request = Net::HTTP.new('httpforever.com', 80) 4 | response = request.get('/') 5 | return unless response.message == 'OK' 6 | 7 | puts response.body.scan(/

.*<\/h2>/) 8 | -------------------------------------------------------------------------------- /io/http10.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | require 'json' 3 | 4 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 5 | query = URI.encode_www_form(params) 6 | request = Net::HTTP.new('localhost', 2000) 7 | headers = { 8 | 'Content-Type': 'application/json', 9 | 'Authorization': 'Bearer ' 10 | } 11 | request.open_timeout = 10 12 | request.read_timeout = 10 13 | request.post('/', params.to_json, headers) 14 | -------------------------------------------------------------------------------- /io/http11.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | require 'json' 3 | 4 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 5 | query = URI.encode_www_form(params) 6 | headers = { 7 | 'Content-Type': 'application/json', 8 | 'Authorization': 'Bearer ' 9 | } 10 | 11 | Net::HTTP.start('localhost', 2000) do |request| 12 | request.open_timeout = 10 13 | request.read_timeout = 10 14 | request.get("/?#{query}", headers) 15 | request.post('/', params.to_json, headers) 16 | end 17 | -------------------------------------------------------------------------------- /io/http2.rb: -------------------------------------------------------------------------------- 1 | require 'open-uri' 2 | 3 | response = URI.open('http://httpforever.com') 4 | puts response.read.scan(/

.*<\/h2>/) 5 | -------------------------------------------------------------------------------- /io/http3.rb: -------------------------------------------------------------------------------- 1 | require 'open-uri' 2 | require 'nokogiri' 3 | 4 | doc = Nokogiri::HTML(URI.open('http://httpforever.com')) 5 | puts doc.search('h2').map { |it| it.text } 6 | -------------------------------------------------------------------------------- /io/http4.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | request = Net::HTTP.new('localhost', 2000) 4 | request.get('/?chave=valor') 5 | -------------------------------------------------------------------------------- /io/http5.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | params = { c1: 'v1', c2: 'v2', c3: 'v3' } 4 | query = URI.encode_www_form(params) 5 | request = Net::HTTP.new('localhost', 2000) 6 | request.get("/?#{query}") 7 | -------------------------------------------------------------------------------- /io/http6.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 4 | query = URI.encode_www_form(params) 5 | request = Net::HTTP.new('localhost', 2000) 6 | request.get("/?#{query}") 7 | -------------------------------------------------------------------------------- /io/http7.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 4 | query = URI.encode_www_form(params) 5 | request = Net::HTTP.new('localhost', 2000) 6 | headers = { 'Content-Type': 'application/json' } 7 | request.get("/?#{query}", headers) 8 | -------------------------------------------------------------------------------- /io/http8.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 4 | query = URI.encode_www_form(params) 5 | request = Net::HTTP.new('localhost', 2000) 6 | headers = { 7 | 'Content-Type': 'application/json', 8 | 'Authorization': 'Bearer ' 9 | } 10 | request.get("/?#{query}", headers) 11 | -------------------------------------------------------------------------------- /io/http9.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | require 'json' 3 | 4 | params = { nome: 'Eustáquio', sobrenome: 'Rangel' } 5 | query = URI.encode_www_form(params) 6 | request = Net::HTTP.new('localhost', 2000) 7 | headers = { 8 | 'Content-Type': 'application/json', 9 | 'Authorization': 'Bearer ' 10 | } 11 | request.post('/', params.to_json, headers) 12 | -------------------------------------------------------------------------------- /io/httparty.rb: -------------------------------------------------------------------------------- 1 | require 'httparty' 2 | 3 | query = { nome: 'Eustáquio', sobrenome: 'Rangel' } 4 | headers = { 5 | 'Content-Type': 'application/json', 6 | 'Authorization': 'Bearer ' 7 | } 8 | 9 | HTTParty.get('http://localhost:2000', query: query, headers: headers) 10 | HTTParty.post('http://localhost:2000', query: query, body: query.to_json) 11 | -------------------------------------------------------------------------------- /io/https.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | begin 4 | host = Net::HTTP.new('postman-echo.com', 443) 5 | host.use_ssl = true 6 | res = host.get('/get?foo=bar') 7 | 8 | puts res.body if res.is_a?(Net::HTTPSuccess) 9 | rescue => exc 10 | puts "erro: #{exc}" 11 | end 12 | -------------------------------------------------------------------------------- /io/io1.rb: -------------------------------------------------------------------------------- 1 | p File.read("teste.txt") 2 | -------------------------------------------------------------------------------- /io/io2.rb: -------------------------------------------------------------------------------- 1 | p File.readlines("teste.txt") 2 | -------------------------------------------------------------------------------- /io/io3.rb: -------------------------------------------------------------------------------- 1 | f = File.open("teste.txt") 2 | 3 | f.each do |linha| 4 | puts linha 5 | end 6 | 7 | f.close 8 | -------------------------------------------------------------------------------- /io/io4.rb: -------------------------------------------------------------------------------- 1 | File.open("teste.txt") do |arquivo| 2 | arquivo.each do |linha| 3 | puts linha 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /io/io7.rb: -------------------------------------------------------------------------------- 1 | require "zip" 2 | require "fileutils" 3 | 4 | myzip = "teste.zip" 5 | File.delete(myzip) if File.exists?(myzip) 6 | 7 | Zip::File.open(myzip,true) do |zipfile| 8 | Dir.glob("[0-9]*.txt") do |file| 9 | puts "Zipando #{file}" 10 | zipfile.add("txts/#{file}", file) 11 | end 12 | end 13 | 14 | Zip::File.open(myzip) do |zipfile| 15 | zipfile.each do |file| 16 | dir = File.dirname(file.name) 17 | puts "Descompactando #{file.name} para #{dir}" 18 | FileUtils.mkpath(dir) if !File.exists?(dir) 19 | zipfile.extract(file.name,file.name) do |entry, file| 20 | puts "Arquivo #{file} existe, apagando ..." 21 | File.delete(file) 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /io/leryaml.rb: -------------------------------------------------------------------------------- 1 | require "yaml" 2 | 3 | result = YAML::load(File.open(ARGV[0])) 4 | p result 5 | -------------------------------------------------------------------------------- /io/nome.rb: -------------------------------------------------------------------------------- 1 | require "open3" 2 | 3 | Open3.popen3("./nome.sh") do |stdin, stdout, stderr, thread| 4 | stdin.puts "taq" 5 | puts stdout.read 6 | puts "Rodei no processo #{thread.pid}" 7 | erro = stderr.read 8 | puts "Ocorreu o erro: #{erro}" if erro.size > 0 9 | end 10 | -------------------------------------------------------------------------------- /io/nome.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Digite seu nome: " 3 | read nome 4 | echo "Oi, $nome!" 5 | -------------------------------------------------------------------------------- /io/novo_teste.txt: -------------------------------------------------------------------------------- 1 | Arquivo de teste 2 | Curso de Ruby 3 | Estamos na terceira linha. 4 | E aqui é a quarta e última. 5 | -------------------------------------------------------------------------------- /io/pop3.rb: -------------------------------------------------------------------------------- 1 | require "net/pop" 2 | require "highline/import" 3 | 4 | user = "eustaquiorangel@gmail.com" 5 | pass = ask("digite sua senha:") { |it| it.echo = "*" } 6 | 7 | pop = Net::POP3.new("pop.gmail.com", 995) 8 | pop.enable_ssl(OpenSSL::SSL::VERIFY_NONE) 9 | 10 | begin 11 | pop.start(user, pass) do |pop| 12 | if pop.mails.empty? 13 | puts "Sem emails!" 14 | return 15 | end 16 | pop.each do |msg| 17 | puts msg.header 18 | end 19 | end 20 | rescue => exception 21 | puts "ERRO: #{exception}" 22 | end 23 | -------------------------------------------------------------------------------- /io/rexml.rb: -------------------------------------------------------------------------------- 1 | require "rexml/document" 2 | 3 | doc = REXML::Document.new 4 | decl = REXML::XMLDecl.new("1.0", "UTF-8") 5 | doc.add decl 6 | 7 | root = REXML::Element.new("alunos") 8 | doc.add_element root 9 | 10 | alunos = [ 11 | [1, "João"], 12 | [2, "José"], 13 | [3, "Antonio"], 14 | [4, "Maria"] 15 | ] 16 | 17 | alunos.each do |info| 18 | aluno = REXML::Element.new("aluno") 19 | id = REXML::Element.new("id") 20 | nome = REXML::Element.new("nome") 21 | 22 | id.text = info[0] 23 | nome.text = info[1] 24 | 25 | aluno.add_element id 26 | aluno.add_element nome 27 | root.add_element aluno 28 | end 29 | 30 | doc.write(File.open("alunos.xml", "w")) 31 | -------------------------------------------------------------------------------- /io/rpcclient.php: -------------------------------------------------------------------------------- 1 | [ 6 | "method" => "POST", 7 | "header" => "Content-Type: text/xml", 8 | "content" => $request 9 | ]]); 10 | 11 | $file = file_get_contents("http://localhost:8081", false, $context); 12 | $response = xmlrpc_decode($file); 13 | 14 | if ($response && xmlrpc_is_fault($response)) { 15 | trigger_error("xmlrpc: ".$response["faultString"]." (".$response["faultCode"]." )"); 16 | } else { 17 | print "O resultado da soma é ".$response["resultado"]."\n"; 18 | } 19 | 20 | // divisão 21 | $request = xmlrpc_encode_request("divide", [11, 4]); 22 | $context = stream_context_create([ 23 | "http" => [ 24 | "method" => "POST", 25 | "header" => "Content-Type: text/xml", 26 | "content" => $request 27 | ]]); 28 | 29 | $file = file_get_contents("http://localhost:8081", false, $context); 30 | $response = xmlrpc_decode($file); 31 | 32 | if ($response && xmlrpc_is_fault($response)) { 33 | trigger_error("xmlrpc: ".$response["faultString"]." (".$response["faultCode"]." )"); 34 | } else { 35 | print "O resultado da divisão é ".$response["resultado"]." e o resto é ".$response["resto"]."\n"; 36 | } 37 | ?> 38 | -------------------------------------------------------------------------------- /io/rpcclient.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import xmlrpc.client 3 | 4 | with xmlrpc.client.ServerProxy("http://localhost:8081/") as server: 5 | result = server.soma(5,3) 6 | print("O resultado da soma é:", result["resultado"]) 7 | 8 | result = server.divide(11,4) 9 | print("O resultado da divisão é", result["resultado"], "e o resto é", result["resto"]) 10 | -------------------------------------------------------------------------------- /io/rpcclient.rb: -------------------------------------------------------------------------------- 1 | require "xmlrpc/client" 2 | 3 | begin 4 | client = XMLRPC::Client.new("localhost", "/RPC2", 8081) 5 | resp = client.call("soma", 5, 3) 6 | puts "O resultado da soma é #{resp['resultado']}" 7 | 8 | resp = client.call("divide", 11, 4) 9 | puts "O resultado da divisao é #{resp['resultado']} e o resto é #{resp['resto']}" 10 | rescue => exception 11 | puts "ERRO: #{exception}" 12 | end 13 | -------------------------------------------------------------------------------- /io/rpcserver.rb: -------------------------------------------------------------------------------- 1 | require "webrick" 2 | require "xmlrpc/server" 3 | 4 | server = XMLRPC::Server.new(8081) 5 | 6 | # somando números 7 | server.add_handler("soma") do |n1, n2| 8 | { "resultado" => n1 + n2 } 9 | end 10 | 11 | # dividindo e retornando o resto 12 | server.add_handler("divide") do |n1, n2| 13 | { "resultado" => n1 / n2, "resto" => n1 % n2 } 14 | end 15 | 16 | server.serve 17 | -------------------------------------------------------------------------------- /io/smtp.rb: -------------------------------------------------------------------------------- 1 | require "net/smtp" 2 | require "highline/import" 3 | 4 | from = "eustaquiorangel@gmail.com" 5 | pass = ask("digite sua senha:") { |it| it.echo = "*" } 6 | to = "eustaquiorangel@gmail.com" 7 | 8 | msg =< exception 25 | puts "ERRO: #{exception}" 26 | puts exception.backtrace 27 | end 28 | -------------------------------------------------------------------------------- /io/sock.rb: -------------------------------------------------------------------------------- 1 | require "socket" 2 | 3 | TCPSocket.open("smtp.mailtrap.io", 465) do |smtp| 4 | puts smtp.gets 5 | smtp.puts "EHLO bluefish.com.br" 6 | puts smtp.gets 7 | end 8 | -------------------------------------------------------------------------------- /io/ssh.rb: -------------------------------------------------------------------------------- 1 | require 'net/ssh' 2 | require 'highline/import' 3 | 4 | host = 'eustaquiorangel.com' 5 | user = 'taq' 6 | pass = ask('digite sua senha') { |it| it.echo = "*" } 7 | 8 | begin 9 | Net::SSH.start(host, user, password: pass) do |session| 10 | puts 'Sessão SSH aberta!' 11 | 12 | session.open_channel do |channel| 13 | puts 'Canal aberto!' 14 | 15 | channel.on_data do |ch, data| 16 | puts "> #{data}" 17 | end 18 | 19 | puts 'Executando comando ...' 20 | channel.exec "ls -lah" 21 | end 22 | session.loop 23 | end 24 | rescue StandardError => exception 25 | puts "ERRO:#{exception}" 26 | puts exception.backtrace 27 | end 28 | -------------------------------------------------------------------------------- /io/tcpclient.rb: -------------------------------------------------------------------------------- 1 | require "socket" 2 | 3 | hash = { um: 1, dois: 2, tres: 3 } 4 | 5 | TCPSocket.open("localhost", 8081) do |server| 6 | server.write [ 7 | 1, 8 | "teste".ljust(10), 9 | Marshal.dump(hash) 10 | ].pack("LA10A*") 11 | end 12 | -------------------------------------------------------------------------------- /io/tcpserver.rb: -------------------------------------------------------------------------------- 1 | require "socket" 2 | 3 | TCPServer.open("localhost", 8081) do |server| 4 | puts "servidor iniciado" 5 | 6 | loop do 7 | puts "aguardando conexão ..." 8 | con = server.accept 9 | puts "conexão recebida!" 10 | con.puts "Sua conexão foi recebida!" 11 | con.close 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /io/tcpserver2.rb: -------------------------------------------------------------------------------- 1 | require "socket" 2 | 3 | TCPServer.open("localhost", 8081) do |server| 4 | puts "servidor iniciado" 5 | 6 | loop do 7 | puts "aguardando conexão ..." 8 | con = server.accept 9 | rst = con.recv(1024).unpack("LA10A*") 10 | int = rst[0] 11 | str = rst[1] 12 | 13 | hash = Marshal.load(rst[2]) 14 | puts "#{int.class}\t: #{int}" 15 | puts "#{str.class}\t: #{str}" 16 | puts "#{hash.class}\t: #{hash}" 17 | con.close 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /io/tcpserver3.rb: -------------------------------------------------------------------------------- 1 | require "socket" 2 | 3 | TCPServer.open("localhost", 8081) do |server| 4 | puts "servidor iniciado" 5 | 6 | loop do 7 | puts "aguardando conexão ..." 8 | con = server.accept 9 | puts "conexão recebida!" 10 | con.puts "Sua conexão foi recebida!" 11 | 12 | while true 13 | str = con.gets 14 | break if str.match?(/sair/) 15 | 16 | puts "você digitou: #{str}" 17 | end 18 | 19 | con.close 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /io/teste.txt: -------------------------------------------------------------------------------- 1 | Arquivo de teste 2 | Curso de Ruby 3 | Estamos na terceira linha. 4 | E aqui é a quarta e última. 5 | -------------------------------------------------------------------------------- /io/teste.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - josé 3 | - joão 4 | - antonio 5 | - maria 6 | -------------------------------------------------------------------------------- /io/teste.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taq/conhecendo-ruby-files/6f86cec4a7a112e3861a11500aa55357fd4e6ac4/io/teste.zip -------------------------------------------------------------------------------- /io/teste2.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - - joão 3 | - josé 4 | - - maria 5 | - antonio 6 | -------------------------------------------------------------------------------- /io/teste3.yml: -------------------------------------------------------------------------------- 1 | --- 2 | josé: 1 3 | joão: 2 4 | antonio: 3 5 | maria: 4 6 | -------------------------------------------------------------------------------- /io/teste4.yml: -------------------------------------------------------------------------------- 1 | --- 2 | pessoas: 3 | joão: 1 4 | josé: 2 5 | maria: 3 6 | antonio: 4 7 | -------------------------------------------------------------------------------- /io/teste5.yml: -------------------------------------------------------------------------------- 1 | --- 2 | development: 3 | adapter: mysql 4 | database: teste_development 5 | username: root 6 | password: test 7 | host: localhost 8 | 9 | test: 10 | adapter: mysql 11 | database: teste_test 12 | username: root 13 | password: test 14 | host: localhost 15 | 16 | production: 17 | adapter: mysql 18 | database: teste_production 19 | username: root 20 | password: test 21 | host: localhost 22 | -------------------------------------------------------------------------------- /io/teste6.yml: -------------------------------------------------------------------------------- 1 | --- 2 | two_words: !ruby/regexp /\A\w+\s\w+\z/i 3 | -------------------------------------------------------------------------------- /io/txts/1.txt: -------------------------------------------------------------------------------- 1 | 111 2 | -------------------------------------------------------------------------------- /io/txts/2.txt: -------------------------------------------------------------------------------- 1 | 222 2 | -------------------------------------------------------------------------------- /io/txts/3.txt: -------------------------------------------------------------------------------- 1 | 333 2 | -------------------------------------------------------------------------------- /io/udpclient.rb: -------------------------------------------------------------------------------- 1 | require 'socket' 2 | 3 | client = UDPSocket.open 4 | client.connect('localhost', 12345) 5 | 6 | loop do 7 | puts "Digite sua mensagem (quit termina, kill finaliza servidor):" 8 | msg = gets 9 | client.send(msg, 0) 10 | break if 'kill,quit'.include? msg.chomp 11 | end 12 | 13 | client.close 14 | -------------------------------------------------------------------------------- /io/udpserver.rb: -------------------------------------------------------------------------------- 1 | require 'socket' 2 | 3 | server = UDPSocket.new 4 | porta = 12345 5 | server.bind('localhost', porta) 6 | puts "Servidor conectado na porta #{porta}, aguardando ..." 7 | 8 | loop do 9 | msg, sender = server.recvfrom(256) 10 | host = sender[3] 11 | puts "Host #{host} enviou um pacote UDP: #{msg}" 12 | break if msg.chomp == 'kill' 13 | end 14 | 15 | puts "Kill recebido, fechando servidor." 16 | server.close 17 | -------------------------------------------------------------------------------- /io/webrick.rb: -------------------------------------------------------------------------------- 1 | require 'webrick' 2 | require 'json' 3 | include WEBrick 4 | 5 | server = WEBrick::HTTPServer.new Port: 2_000, DocumentRoot: Dir.pwd 6 | server.mount_proc '/' do |req, res| 7 | puts "\nURI: #{req.request_uri}" 8 | puts "Request method: #{req.request_method}" 9 | 10 | req.header.slice('content-type', 'authorization').each do |key, value| 11 | puts "#{key}: #{value.join}" 12 | end 13 | 14 | if req.body 15 | json = JSON.parse(req.body) 16 | p json 17 | end 18 | puts "\n" 19 | 20 | res.body = 'Hello!' 21 | end 22 | 23 | trap("INT") { server.shutdown } 24 | server.start 25 | -------------------------------------------------------------------------------- /io/xml2.rb: -------------------------------------------------------------------------------- 1 | require "rexml/document" 2 | 3 | doc = REXML::Document.new(File.open("alunos.xml")) 4 | 5 | doc.elements.each("alunos/aluno") do |aluno| 6 | puts "#{aluno.elements['id'].text} - #{aluno.elements['nome'].text}" 7 | end 8 | -------------------------------------------------------------------------------- /io/xml3.rb: -------------------------------------------------------------------------------- 1 | require "rexml/document" 2 | 3 | doc = REXML::Document.new(File.open("alunos.xml")) 4 | 5 | doc.elements.to_a("//aluno").each do |aluno| 6 | puts "#{aluno.elements['id'].text} - #{aluno.elements['nome'].text}" 7 | end 8 | -------------------------------------------------------------------------------- /io/xml4.rb: -------------------------------------------------------------------------------- 1 | require "rexml/document" 2 | 3 | doc = REXML::Document.new(File.open("alunos.xml")) 4 | root = doc.root 5 | aluno = root.elements["aluno[2]"] 6 | 7 | puts "#{aluno.elements['id'].text} - #{aluno.elements['nome'].text}" 8 | -------------------------------------------------------------------------------- /io/xml5.rb: -------------------------------------------------------------------------------- 1 | require "builder" 2 | 3 | alunos = { 4 | 1 => "João", 5 | 2 => "José", 6 | 3 => "Antonio", 7 | 4 => "Maria" 8 | } 9 | 10 | xml = Builder::XmlMarkup.new(indent: 2) 11 | xml.instruct! 12 | 13 | xml.alunos do 14 | alunos.each do |key, value| 15 | xml.aluno do 16 | xml.id key 17 | xml.nome value 18 | end 19 | end 20 | end 21 | 22 | # para gravar o arquivo 23 | File.open("alunos.xml", "w") do |file| 24 | file << xml.target! 25 | end 26 | -------------------------------------------------------------------------------- /io/xml6.rb: -------------------------------------------------------------------------------- 1 | require "nokogiri" 2 | 3 | doc = Nokogiri::XML(File.open("alunos.xml")) 4 | 5 | doc.search("aluno").each do |node| 6 | puts node.search("id").text + " - " + node.search("nome").text 7 | end 8 | -------------------------------------------------------------------------------- /io/xslt.rb: -------------------------------------------------------------------------------- 1 | require "xml/xslt" 2 | 3 | xslt = XML::XSLT.new 4 | xslt.xsl = "alunos.xsl" 5 | xslt.xml = "alunos.xml" 6 | xslt.save("alunos.html") 7 | puts xslt.serve 8 | -------------------------------------------------------------------------------- /jruby/Carro.java: -------------------------------------------------------------------------------- 1 | // Carro.java 2 | public class Carro { 3 | private String marca, cor, modelo; 4 | private int tanque; 5 | 6 | public Carro(String marca, String cor, String modelo, int tanque) { 7 | this.marca = marca; 8 | this.cor = cor; 9 | this.modelo = modelo; 10 | this.tanque = tanque; 11 | } 12 | 13 | public String toString() { 14 | return "Marca: " + this.marca + "\n" + 15 | "Cor: " + this.cor + "\n" + 16 | "Modelo:" + this.modelo + "\n" + 17 | "Tanque:" + this.tanque; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /jruby/Double.java: -------------------------------------------------------------------------------- 1 | import org.jruby.*; 2 | import org.jruby.embed.LocalVariableBehavior; 3 | import org.jruby.embed.PathType; 4 | import org.jruby.embed.ScriptingContainer; 5 | 6 | public class Double { 7 | public static void main(String args[]) { 8 | try { 9 | ScriptingContainer container = new ScriptingContainer(LocalVariableBehavior.PERSISTENT); 10 | container.put("num", 2); 11 | 12 | String script = "doublejava.rb"; 13 | System.out.println("Chamando o script " + script + " ..."); 14 | long value = (Long) container.runScriptlet(PathType.CLASSPATH, script); 15 | System.out.println("Resultado: " + value); 16 | } catch(Exception e) { 17 | System.err.println("Erro: " + e.getMessage()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /jruby/carro_java.rb: -------------------------------------------------------------------------------- 1 | # carro.rb 2 | require "java" 3 | java_import("Carro") 4 | 5 | carro = Carro.new("VW", "prata", "polo", 40) 6 | puts carro 7 | 8 | class Mach5 < Carro 9 | attr_reader :tanque_oxigenio 10 | 11 | def initialize(marca, cor, modelo, tanque, tanque_oxigenio) 12 | super(marca, cor, modelo, tanque) 13 | @tanque_oxigenio = tanque_oxigenio 14 | end 15 | 16 | def to_s 17 | "#{super}\nTanque oxigenio: #{@tanque_oxigenio}" 18 | end 19 | end 20 | 21 | puts "*" * 25 22 | mach5 = Mach5.new("PopsRacer", "branco", "Mach5", 50, 10) 23 | puts mach5 24 | -------------------------------------------------------------------------------- /jruby/doublejava.rb: -------------------------------------------------------------------------------- 1 | puts "Dobrando #{num} aqui no Ruby ..." 2 | num * 2 3 | -------------------------------------------------------------------------------- /jruby/gui.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "java" 3 | 4 | %w(JFrame JLabel JPanel JButton).each { |it| java_import("javax.swing.#{it}") } 5 | 6 | class Alistener 7 | include java.awt.event.ActionListener 8 | def actionPerformed(event) 9 | puts "Botão clicado!" 10 | end 11 | end 12 | listener = Alistener.new 13 | 14 | frame = JFrame.new 15 | label = JLabel.new("Clique no botão!") 16 | panel = JPanel.new 17 | 18 | button = JButton.new("Clique em mim!") 19 | button.addActionListener(listener) 20 | 21 | panel.setLayout(java.awt.GridLayout.new(2,1)) 22 | panel.add(label) 23 | panel.add(button) 24 | 25 | frame.setTitle("Exemplo de JRuby") 26 | frame.getContentPane().add(panel) 27 | frame.pack 28 | frame.defaultCloseOperation = JFrame::EXIT_ON_CLOSE 29 | frame.setVisible(true) 30 | -------------------------------------------------------------------------------- /jruby/jruby.rb: -------------------------------------------------------------------------------- 1 | puts "digite seu nome:" 2 | nome = gets.chomp 3 | puts "oi, #{nome}!" 4 | -------------------------------------------------------------------------------- /modulos/Namespace.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exemplo de namespace utilizando duas classes com o mesmo nome, mas com 3 | * namespaces diferentes 4 | */ 5 | 6 | public class Namespace { 7 | public static void main(String args[]) { 8 | System.out.println(com.eustaquiorangel.paulista.Pessoa.comidaPreferida()); 9 | System.out.println(com.eustaquiorangel.gaucho.Pessoa.comidaPreferida()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /modulos/ancestors.rb: -------------------------------------------------------------------------------- 1 | class C 2 | def x 3 | 'x' 4 | end 5 | end 6 | 7 | module M 8 | def x 9 | "[#{super}]" 10 | end 11 | 12 | def y 13 | 'y' 14 | end 15 | end 16 | 17 | class C 18 | include M 19 | end 20 | 21 | p C.ancestors 22 | c = C.new 23 | puts c.x 24 | puts c.y 25 | -------------------------------------------------------------------------------- /modulos/binding.rb: -------------------------------------------------------------------------------- 1 | module Automovel 2 | def ligar 3 | puts "Ligando automóvel #{@marca}" 4 | end 5 | end 6 | 7 | module Radio 8 | def ligar 9 | puts "Ligando rádio #{@marca}" 10 | end 11 | end 12 | 13 | class Carro 14 | include Automovel 15 | include Radio 16 | 17 | def initialize 18 | @marca = :vw 19 | end 20 | 21 | def ligar 22 | Automovel.instance_method(:ligar).bind(self).call 23 | super 24 | end 25 | end 26 | 27 | Carro.new.ligar 28 | -------------------------------------------------------------------------------- /modulos/binding2.rb: -------------------------------------------------------------------------------- 1 | require 'erb' 2 | 3 | class User 4 | def initialize 5 | @name = 'taq' 6 | end 7 | 8 | def resolve_binding 9 | binding 10 | end 11 | end 12 | 13 | user = User.new 14 | erb = ERB.new "Olá, <%= @name %>!" 15 | 16 | puts erb.result(user.resolve_binding) 17 | -------------------------------------------------------------------------------- /modulos/com/eustaquiorangel/gaucho/Pessoa.java: -------------------------------------------------------------------------------- 1 | // localizado em com/eustaquiorangel/gaucho/Pessoa.java 2 | package com.eustaquiorangel.gaucho; 3 | 4 | public class Pessoa { 5 | public static String comidaPreferida() { 6 | return "churrasco"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /modulos/com/eustaquiorangel/paulista/Pessoa.java: -------------------------------------------------------------------------------- 1 | // localizado em com/eustaquiorangel/paulista/Pessoa.java 2 | package com.eustaquiorangel.paulista; 3 | 4 | public class Pessoa { 5 | public static String comidaPreferida() { 6 | return "pizza"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /modulos/inception.rb: -------------------------------------------------------------------------------- 1 | module Inception 2 | def self.hello 3 | puts 'hello' 4 | end 5 | 6 | def self.world 7 | puts 'world' 8 | end 9 | end 10 | 11 | Inception.hello 12 | Inception.world 13 | -------------------------------------------------------------------------------- /modulos/inception1.rb: -------------------------------------------------------------------------------- 1 | module Inception 2 | def self.hello 3 | puts 'hello' 4 | end 5 | 6 | def self.world 7 | puts 'world' 8 | end 9 | end 10 | 11 | Inception.hello 12 | Inception.world 13 | -------------------------------------------------------------------------------- /modulos/inception2.rb: -------------------------------------------------------------------------------- 1 | module Inception 2 | extend self 3 | 4 | def hello 5 | puts 'hello' 6 | end 7 | 8 | def world 9 | puts 'world' 10 | end 11 | end 12 | 13 | Inception.hello 14 | Inception.world 15 | -------------------------------------------------------------------------------- /modulos/interface.rb: -------------------------------------------------------------------------------- 1 | module AbstractInterface 2 | class NotImplementedError < StandardError 3 | def initialize(*methods) 4 | super "You must implement the following methods: #{methods.join(', ')}" 5 | end 6 | end 7 | 8 | def AbstractInterface.check_methods(klass, other, methods) 9 | return if other.class == Module 10 | 11 | TracePoint.new(:end) do |tp| 12 | return if tp.self != other || methods.nil? 13 | missing = methods.select { |it| !other.instance_methods.include?(it) } 14 | raise NotImplementedError.new(missing) if missing.any? 15 | end.enable 16 | end 17 | 18 | module ClassMethods 19 | def abstract_method(*args) 20 | return @abstract_method if !args 21 | @abstract_method ||= [] 22 | @abstract_method.push(*args) 23 | end 24 | 25 | def included(other) 26 | AbstractInterface.check_methods(self, other, @abstract_method) 27 | end 28 | 29 | def check_methods(klass, other, methods) 30 | AbstractInterface.check_methods(klass, other, methods) 31 | end 32 | end 33 | 34 | def self.included(other) 35 | check_methods(self, other, @abstract_method) 36 | other.extend ClassMethods 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /modulos/mod1.rb: -------------------------------------------------------------------------------- 1 | class Primata 2 | def come 3 | puts "Nham!" 4 | end 5 | 6 | def dorme 7 | puts "Zzzzzz..." 8 | end 9 | end 10 | 11 | class Humano < Primata 12 | def conecta_na_web 13 | puts "Login ... senha ..." 14 | end 15 | end 16 | 17 | module Ave 18 | def voa 19 | puts "Para o alto, e avante!" 20 | end 21 | end 22 | 23 | class Mutante < Humano 24 | include Ave 25 | end 26 | 27 | mutante = Mutante.new 28 | mutante.come 29 | mutante.dorme 30 | mutante.conecta_na_web 31 | mutante.voa 32 | -------------------------------------------------------------------------------- /modulos/mod2.rb: -------------------------------------------------------------------------------- 1 | class Primata 2 | def come 3 | puts "Nham!" 4 | end 5 | 6 | def dorme 7 | puts "Zzzzzz..." 8 | end 9 | end 10 | 11 | class Humano < Primata 12 | def conecta_na_web 13 | puts "Login ... senha ..." 14 | end 15 | end 16 | 17 | module Ave 18 | def voa 19 | puts "Para o alto, e avante!" 20 | end 21 | end 22 | 23 | class Mutante < Humano 24 | end 25 | 26 | mutante = Mutante.new 27 | mutante.extend(Ave) 28 | mutante.come 29 | mutante.dorme 30 | mutante.conecta_na_web 31 | mutante.voa 32 | 33 | mutante2 = Mutante.new 34 | mutante2.voa 35 | -------------------------------------------------------------------------------- /modulos/mod3.rb: -------------------------------------------------------------------------------- 1 | class CaixaDeParafusos 2 | include Comparable 3 | attr_reader :quantidade 4 | 5 | def initialize(quantidade) 6 | @quantidade = quantidade 7 | end 8 | 9 | def <=>(outra) 10 | self.quantidade <=> outra.quantidade 11 | end 12 | end 13 | 14 | caixa1 = CaixaDeParafusos.new(10) 15 | caixa2 = CaixaDeParafusos.new(20) 16 | caixa3 = CaixaDeParafusos.new(10) 17 | 18 | puts caixa1 < caixa2 19 | puts caixa2 > caixa3 20 | puts caixa1 == caixa3 21 | puts caixa3 > caixa2 22 | puts caixa1.between?(caixa3, caixa2) 23 | -------------------------------------------------------------------------------- /modulos/mod4.rb: -------------------------------------------------------------------------------- 1 | class Parafuso 2 | attr_reader :polegadas 3 | 4 | def initialize(polegadas) 5 | @polegadas = polegadas 6 | end 7 | 8 | def <=>(outro) 9 | self.polegadas <=> outro.polegadas 10 | end 11 | 12 | def to_s 13 | "Parafuso #{object_id} com #{@polegadas}\"" 14 | end 15 | end 16 | 17 | class CaixaDeParafusos 18 | include Enumerable 19 | 20 | def initialize 21 | @parafusos = [] 22 | end 23 | 24 | def <<(parafuso) 25 | @parafusos << parafuso 26 | end 27 | 28 | def each 29 | @parafusos.each { |it| yield(it) } 30 | end 31 | end 32 | 33 | caixa = CaixaDeParafusos.new 34 | caixa << Parafuso.new(1) 35 | caixa << Parafuso.new(2) 36 | caixa << Parafuso.new(3) 37 | 38 | puts "o menor parafuso na caixa é: #{caixa.min}" 39 | puts "o maior parafuso na caixa é: #{caixa.max}" 40 | puts "os parafusos com medidas par são: #{caixa.select { |it| it.polegadas % 2 == 0}.join(',')}" 41 | puts "duplicando a caixa: #{caixa.map { |it| Parafuso.new(it.polegadas * 2).to_s }}" 42 | -------------------------------------------------------------------------------- /modulos/mod5.rb: -------------------------------------------------------------------------------- 1 | module Paulista 2 | class Pessoa 3 | def comida_preferida 4 | "pizza" 5 | end 6 | end 7 | end 8 | 9 | module Gaucho 10 | class Pessoa 11 | def comida_preferida 12 | "churrasco" 13 | end 14 | end 15 | end 16 | 17 | pessoa1 = Paulista::Pessoa.new 18 | pessoa2 = Gaucho::Pessoa.new 19 | 20 | puts pessoa1.comida_preferida 21 | puts pessoa2.comida_preferida 22 | -------------------------------------------------------------------------------- /modulos/mod6.rb: -------------------------------------------------------------------------------- 1 | require 'singleton' 2 | 3 | class Teste 4 | include Singleton 5 | end 6 | 7 | begin 8 | Teste.new 9 | rescue StandardError => e 10 | puts "Não consegui criar usando new: #{e}" 11 | end 12 | 13 | puts Teste.instance.object_id 14 | puts Teste.instance.object_id 15 | -------------------------------------------------------------------------------- /modulos/mod7.rb: -------------------------------------------------------------------------------- 1 | module TesteMod 2 | module ClassMethods 3 | def class_method 4 | puts "Esse é um método da classe!" 5 | end 6 | 7 | private 8 | 9 | def private_method 10 | puts "Esse é um método privado de classe!" 11 | end 12 | end 13 | 14 | def self.included(where) 15 | where.extend(ClassMethods) 16 | end 17 | 18 | def instance_method 19 | puts "Esse é um método de instância!" 20 | end 21 | end 22 | 23 | class TesteCls 24 | include TesteMod 25 | end 26 | 27 | t = TesteCls.new 28 | t.instance_method 29 | TesteCls.class_method 30 | TesteCls.private_method 31 | -------------------------------------------------------------------------------- /modulos/overmod.rb: -------------------------------------------------------------------------------- 1 | module Automovel 2 | def ligar 3 | puts "ligando automóvel" 4 | end 5 | end 6 | 7 | module Radio 8 | def ligar 9 | puts "ligando rádio" 10 | end 11 | end 12 | 13 | class Carro 14 | include Automovel 15 | include Radio 16 | end 17 | 18 | c = Carro.new 19 | c.ligar 20 | -------------------------------------------------------------------------------- /modulos/prepend.rb: -------------------------------------------------------------------------------- 1 | class C 2 | def x 3 | 'x' 4 | end 5 | end 6 | 7 | module M 8 | def x 9 | "[#{super}]" 10 | end 11 | 12 | def y 13 | 'y' 14 | end 15 | end 16 | 17 | class C 18 | prepend M 19 | end 20 | 21 | p C.ancestors # => [M, C, Object, Kernel, BasicObject] 22 | c = C.new 23 | 24 | puts c.x # => [x] 25 | puts c.y # => y 26 | -------------------------------------------------------------------------------- /modulos/refinements.rb: -------------------------------------------------------------------------------- 1 | module NewHashToS 2 | refine Hash do 3 | def to_s 4 | map do |key, val| 5 | "[#{key}=#{val}]" 6 | end.join(',') 7 | end 8 | end 9 | end 10 | 11 | class Primeira 12 | def initialize(values) 13 | puts "primeira: #{values}" 14 | end 15 | end 16 | 17 | class Segunda 18 | using NewHashToS 19 | 20 | def initialize(values) 21 | puts "segunda: #{values}" 22 | end 23 | 24 | def self.used_refinements 25 | Module.used_refinements 26 | end 27 | end 28 | 29 | class Terceira 30 | def initialize(values) 31 | puts "terceira: #{values}" 32 | end 33 | end 34 | 35 | values = { a: 1, b: 2, c: 3 } 36 | 37 | Primeira.new(values) 38 | Segunda.new(values) 39 | Terceira.new(values) 40 | 41 | puts "no contexto principal: #{values}" 42 | using NewHashToS 43 | puts "no contexto principal, refinado: #{values}" 44 | 45 | p NewHashToS.refinements 46 | p NewHashToS.refinements[0].refined_class 47 | p NewHashToS.refinements[0].instance_methods(false) 48 | p Module.used_refinements 49 | p Segunda.used_refinements 50 | -------------------------------------------------------------------------------- /modulos/tpoint.rb: -------------------------------------------------------------------------------- 1 | TracePoint.new(:class,:end,:call) do |tp| 2 | puts "Disparado por #{tp.self} no arquivo #{tp.path} na linha #{tp.lineno}" 3 | end.enable 4 | 5 | module Paulista 6 | class Pessoa 7 | end 8 | end 9 | p = Paulista::Pessoa.new 10 | -------------------------------------------------------------------------------- /rake/1.txt: -------------------------------------------------------------------------------- 1 | 111 2 | -------------------------------------------------------------------------------- /rake/2.txt: -------------------------------------------------------------------------------- 1 | 222 2 | -------------------------------------------------------------------------------- /rake/3.txt: -------------------------------------------------------------------------------- 1 | 333 2 | -------------------------------------------------------------------------------- /rake/Rakefile: -------------------------------------------------------------------------------- 1 | Rakefile-5 -------------------------------------------------------------------------------- /rake/Rakefile-1: -------------------------------------------------------------------------------- 1 | desc "Lista os arquivos" 2 | task :list do 3 | Dir.glob("*.txt") do |file| 4 | puts "encontrei o arquivo: #{file}" 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /rake/Rakefile-2: -------------------------------------------------------------------------------- 1 | task default: :list 2 | 3 | desc "Lista os arquivos" 4 | task :list do 5 | Dir.glob("*.txt") do |file| 6 | puts "encontrei o arquivo: #{file}" 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /rake/Rakefile-3: -------------------------------------------------------------------------------- 1 | task default: "files:list" 2 | 3 | namespace :files do 4 | desc "Lista os arquivos candidatos à compactação" 5 | task :list do 6 | Dir.glob("*.txt") do |file| 7 | puts "encontrei o arquivo: #{file}" 8 | end 9 | end 10 | end 11 | 12 | namespace :zip do 13 | desc "Lista os arquivos compactados" 14 | task :list do 15 | Dir.glob("*.zip") do |file| 16 | puts "encontrei o arquivo: #{file}" 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /rake/Rakefile-4: -------------------------------------------------------------------------------- 1 | require "open3" 2 | 3 | task default: "files:list" 4 | 5 | filemask = "*.txt" 6 | zipfile = "rake.zip" 7 | 8 | namespace :files do 9 | desc "Lista os arquivos candidatos à compactação" 10 | task :list do 11 | Dir.glob(filemask) do |file| 12 | puts "encontrei o arquivo: #{file}" 13 | end 14 | end 15 | end 16 | 17 | namespace :zip do 18 | desc "Lista os arquivos compactados" 19 | task :list do 20 | Dir.glob(zipfile) do |file| 21 | puts "encontrei o arquivo: #{file}" 22 | end 23 | end 24 | 25 | desc "Apaga o arquivo .zip anterior" 26 | task :clean do 27 | puts "Apagando o arquivo #{zipfile}, se existir ..." 28 | File.delete(zipfile) if File.exists?(zipfile) 29 | end 30 | 31 | desc "Cria o arquivo .zip" 32 | task build: :clean do 33 | puts "Criando o arquivo #{zipfile} ..." 34 | list = Dir.glob(filemask).sort.join(" ") 35 | puts "Adicionando os arquivos #{list} ..." 36 | stdin, stdout, stderr = Open3.popen3("zip #{zipfile} #{list}") 37 | error = stderr.read 38 | if error.size == 0 39 | puts "Arquivo criado com sucesso." 40 | else 41 | puts "Erro criando o arquivo: #{error}" 42 | end 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /rake/Rakefile-5: -------------------------------------------------------------------------------- 1 | require "open3" 2 | 3 | task default: "files:list" 4 | filemask = "*.txt" 5 | zipfile = "rake.zip" 6 | 7 | namespace :files do 8 | desc "Lista os arquivos candidatos à compactação" 9 | task :list do 10 | Dir.glob(filemask) do |file| 11 | puts "encontrei o arquivo: #{file}" 12 | end 13 | end 14 | end 15 | 16 | namespace :zip do 17 | desc "Lista os arquivos compactados" 18 | task :list do 19 | Dir.glob(zipfile) do |file| 20 | puts "encontrei o arquivo: #{file}" 21 | end 22 | end 23 | 24 | desc "Apaga o arquivo .zip anterior" 25 | task :clean do 26 | puts "Apagando o arquivo #{zipfile}, se existir ..." 27 | File.delete(zipfile) if File.exists?(zipfile) 28 | end 29 | 30 | desc "Cria o arquivo .zip" 31 | task build: :clean do 32 | puts "Criando o arquivo #{zipfile} ..." 33 | list = Dir.glob(filemask).sort.join(", ") 34 | puts "Adicionando os arquivos #{list} ..." 35 | stdin, stdout, stderr = Open3.popen3("zip #{zipfile} #{list}") 36 | puts stderr.read.size == 0 ? "Arquivo criado com sucesso." : "Erro criando o arquivo: #{error}" 37 | end 38 | 39 | desc "Cria o arquivo rake.zip se não estiver criado" 40 | file "rake.zip" do 41 | Rake::Task["zip:build"].invoke 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /rake/Rakefile-6: -------------------------------------------------------------------------------- 1 | require "open3" 2 | 3 | task default: "files:list" 4 | filemask = "*.txt" 5 | zipfile = "rake.zip" 6 | 7 | namespace :files do 8 | desc "Lista os arquivos candidatos à compactação" 9 | task :list do 10 | Dir.glob(filemask) do |file| 11 | puts "encontrei o arquivo: #{file}" 12 | end 13 | end 14 | end 15 | 16 | namespace :zip do 17 | desc "Lista os arquivos compactados" 18 | task :list do 19 | Dir.glob(zipfile) do |file| 20 | puts "encontrei o arquivo: #{file}" 21 | end 22 | end 23 | 24 | desc "Apaga o arquivo .zip anterior" 25 | task :clean do 26 | puts "Apagando o arquivo #{zipfile}, se existir ..." 27 | File.delete(zipfile) if File.exists?(zipfile) 28 | end 29 | 30 | desc "Cria o arquivo .zip" 31 | task build: :clean do 32 | puts "Criando o arquivo #{zipfile} ..." 33 | list = Rake::FileList[filemask] 34 | list.exclude(/\A[a-zA-Z]+/) 35 | list = list.sort.join(", ") 36 | 37 | puts "Adicionando os arquivos #{list} ..." 38 | stdin, stdout, stderr = Open3.popen3("zip #{zipfile} #{list}") 39 | puts stderr.read.size == 0 ? "Arquivo criado com sucesso." : "Erro criando o arquivo: #{error}" 40 | end 41 | 42 | desc "Cria o arquivo rake.zip se não estiver criado" 43 | file "rake.zip" do 44 | Rake::Task["zip:build"].invoke 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /rake/Rakefile-7: -------------------------------------------------------------------------------- 1 | require "open3" 2 | task default: "files:list" 3 | filemask = "*.txt" 4 | zipfile = "rake.zip" 5 | 6 | namespace :files do 7 | desc "Lista os arquivos candidatos à compactação" 8 | task :list do 9 | Dir.glob(filemask) do |file| 10 | puts "encontrei o arquivo: #{file}" 11 | end 12 | end 13 | end 14 | namespace :zip do 15 | desc "Lista os arquivos compactados" 16 | task :list do 17 | Dir.glob(zipfile) do |file| 18 | puts "encontrei o arquivo: #{file}" 19 | end 20 | end 21 | desc "Apaga o arquivo .zip anterior" 22 | task :clean do 23 | puts "Apagando o arquivo #{zipfile}, se existir ..." 24 | File.delete(zipfile) if File.exists?(zipfile) 25 | end 26 | desc "Cria o arquivo .zip" 27 | task build: :clean do 28 | puts "Criando o arquivo #{zipfile} ..." 29 | list = Rake::FileList[filemask] 30 | list.exclude(/\A[a-zA-Z]+/) 31 | list = list.sort.join(", ") 32 | 33 | puts "Adicionando os arquivos #{list} ..." 34 | stdin, stdout, stderr = Open3.popen3("zip #{zipfile} #{list}") 35 | puts stderr.read.size == 0 ? "Arquivo criado com sucesso." : "Erro criando o arquivo: #{error}" 36 | end 37 | desc "Cria o arquivo rake.zip se não estiver criado" 38 | file "rake.zip" do 39 | Rake::Task["zip:build"].invoke 40 | end 41 | desc "Cria o arquivo" 42 | rule ".zip" do |file| 43 | zipfile = file.name 44 | Rake::Task["zip:build"].invoke 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /rake/Rakefile-8: -------------------------------------------------------------------------------- 1 | require "open3" 2 | require "fileutils" 3 | 4 | task default: "files:list" 5 | filemask = "*.txt" 6 | zipfile = "rake.zip" 7 | 8 | namespace :files do 9 | desc "Lista os arquivos candidatos à compactação" 10 | task :list do 11 | Dir.glob(filemask) do |file| 12 | puts "encontrei o arquivo: #{file}" 13 | end 14 | end 15 | end 16 | 17 | namespace :zip do 18 | desc "Lista os arquivos compactados" 19 | task :list do 20 | Dir.glob(zipfile) do |file| 21 | puts "encontrei o arquivo: #{file}" 22 | end 23 | end 24 | 25 | desc "Apaga o arquivo .zip anterior" 26 | task :clean do 27 | puts "Apagando o arquivo #{zipfile}, se existir ..." 28 | File.delete(zipfile) if File.exists?(zipfile) 29 | end 30 | 31 | desc "Cria o arquivo .zip" 32 | task build: :clean do 33 | puts "Criando o arquivo #{zipfile} ..." 34 | list = Rake::FileList[filemask] 35 | list.exclude(/\A[a-zA-Z]+/) 36 | list = list.sort.join(", ") 37 | 38 | puts "Adicionando os arquivos #{list} ..." 39 | stdin, stdout, stderr = Open3.popen3("zip #{zipfile} #{list}") 40 | puts stderr.read.size == 0 ? "Arquivo criado com sucesso." : "Erro criando o arquivo: #{error}" 41 | end 42 | 43 | desc "Cria o arquivo rake.zip se não estiver criado" 44 | file "rake.zip" do 45 | Rake::Task["zip:build"].invoke 46 | end 47 | 48 | desc "Cria o arquivo" 49 | rule ".zip" do |file| 50 | zipfile = file.name 51 | Rake::Task["zip:build"].invoke 52 | end 53 | 54 | Rake::Task["zip:build"].enhance do 55 | newfile = "rake.#{Time.now.strftime('%H%M%S')}.zip" 56 | puts "Renomeando para #{newfile} ..." 57 | FileUtils.mv zipfile, newfile 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /rake/a.txt: -------------------------------------------------------------------------------- 1 | aaa 2 | -------------------------------------------------------------------------------- /rake/b.txt: -------------------------------------------------------------------------------- 1 | bbb 2 | -------------------------------------------------------------------------------- /rake/c.txt: -------------------------------------------------------------------------------- 1 | ccc 2 | -------------------------------------------------------------------------------- /rake/dependent.rake: -------------------------------------------------------------------------------- 1 | require "open3" 2 | 3 | task default: "files:list" 4 | 5 | FILEMASK = "*.txt" 6 | ZIPFILE = "rake.zip" 7 | 8 | namespace :files do 9 | desc "Lista os arquivos candidatos à compactação" 10 | task :list do 11 | Dir.glob(FILEMASK) do |file| 12 | puts "encontrei o arquivo: #{file}" 13 | end 14 | end 15 | end 16 | 17 | namespace :zip do 18 | desc "Lista os arquivos compactados" 19 | task :list do 20 | Dir.glob(ZIPFILE) do |file| 21 | puts "encontrei o arquivo: #{file}" 22 | end 23 | end 24 | 25 | desc "Apaga o arquivo .zip anterior" 26 | task :clean do 27 | puts "Apagando o arquivo #{ZIPFILE}, se existir ..." 28 | File.delete(ZIPFILE) if File.exists?(ZIPFILE) 29 | end 30 | 31 | desc "Cria o arquivo .zip" 32 | task build: :clean do 33 | puts "Criando o arquivo #{ZIPFILE} ..." 34 | list = Dir.glob(FILEMASK).sort.join(", ") 35 | puts "Adicionando os arquivos #{list} ..." 36 | stdin, stdout, stderr = Open3.popen3("zip #{ZIPFILE} #{list}") 37 | error = stderr.read 38 | if error.size == 0 39 | puts "Arquivo criado com sucesso." 40 | else 41 | puts "Erro criando o arquivo: #{error}" 42 | end 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /rbs/Steepfile: -------------------------------------------------------------------------------- 1 | D = Steep::Diagnostic 2 | 3 | target :lib do 4 | signature "." 5 | check "." 6 | end 7 | -------------------------------------------------------------------------------- /rbs/Steepfile.init: -------------------------------------------------------------------------------- 1 | # D = Steep::Diagnostic 2 | # 3 | # target :lib do 4 | # signature "sig" 5 | # 6 | # check "lib" # Directory name 7 | # check "Gemfile" # File name 8 | # check "app/models/**/*.rb" # Glob 9 | # # ignore "lib/templates/*.rb" 10 | # 11 | # # library "pathname" # Standard libraries 12 | # # library "strong_json" # Gems 13 | # 14 | # # configure_code_diagnostics(D::Ruby.default) # `default` diagnostics setting (applies by default) 15 | # # configure_code_diagnostics(D::Ruby.strict) # `strict` diagnostics setting 16 | # # configure_code_diagnostics(D::Ruby.lenient) # `lenient` diagnostics setting 17 | # # configure_code_diagnostics(D::Ruby.silent) # `silent` diagnostics setting 18 | # # configure_code_diagnostics do |hash| # You can setup everything yourself 19 | # # hash[D::Ruby::NoMethod] = :information 20 | # # end 21 | # end 22 | 23 | # target :test do 24 | # signature "sig", "sig-private" 25 | # 26 | # check "test" 27 | # 28 | # # library "pathname" # Standard libraries 29 | # end 30 | -------------------------------------------------------------------------------- /rbs/carro.naked.rbs: -------------------------------------------------------------------------------- 1 | # Classes 2 | class Carro 3 | attr_reader marca: untyped 4 | attr_reader modelo: untyped 5 | attr_reader tanque: untyped 6 | attr_accessor cor: untyped 7 | def initialize: (untyped marca, untyped modelo, untyped cor, untyped tanque) -> untyped 8 | end 9 | -------------------------------------------------------------------------------- /rbs/carro.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | 5 | def initialize(marca, modelo, cor, tanque) 6 | @marca = marca 7 | @modelo = modelo 8 | @cor = cor 9 | @tanque = tanque 10 | end 11 | end 12 | 13 | Carro.new('fiat', 'pulse', 'branco', 40) 14 | -------------------------------------------------------------------------------- /rbs/carro.rbs: -------------------------------------------------------------------------------- 1 | # Classes 2 | class Carro 3 | attr_reader marca: String 4 | attr_reader modelo: String 5 | attr_reader tanque: Integer 6 | attr_accessor cor: String 7 | def initialize: (String marca, String modelo, String cor, Integer tanque) -> Integer 8 | end 9 | -------------------------------------------------------------------------------- /testing/Guardfile: -------------------------------------------------------------------------------- 1 | guard :minitest do 2 | watch(%r{^spec/(.*)_spec\.rb$}) 3 | watch(%r{^(.+)\.rb$}) { |it| "spec/#{it[1]}_spec.rb" } 4 | end 5 | -------------------------------------------------------------------------------- /testing/calc.rb: -------------------------------------------------------------------------------- 1 | class Calculadora 2 | def soma(a, b) 3 | a + b 4 | end 5 | 6 | def subtrai(a, b) 7 | a - b 8 | end 9 | 10 | def media(colecao) 11 | val = colecao.valores 12 | val.reduce(:+) / val.size.to_f 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /testing/calc_bench_spec.rb: -------------------------------------------------------------------------------- 1 | require 'minitest/autorun' 2 | require 'minitest/benchmark' 3 | require_relative 'calc' 4 | 5 | describe 'Calculadora Benchmark' do 6 | before do 7 | @calculadora = Calculadora.new 8 | end 9 | 10 | bench_performance_constant 'primeiro algoritmo', 0.001 do |n| 11 | 100.times do |v| 12 | @calculadora.soma(n, v) 13 | end 14 | end 15 | 16 | bench_performance_constant 'segundo algoritmo', 0.001 do |n| 17 | 100.times do |v| 18 | @calculadora.soma(v, n) 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /testing/calc_spec.rb: -------------------------------------------------------------------------------- 1 | require 'minitest/autorun' 2 | require_relative 'calc' 3 | 4 | describe Calculadora do 5 | before do 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | after do 10 | @calculadora = nil 11 | end 12 | 13 | describe 'objeto' do 14 | it 'deve ser do tipo de Calculadora' do 15 | expect(@calculadora).must_be_kind_of Calculadora 16 | end 17 | 18 | it 'deve ter um método para somar' do 19 | expect(@calculadora).must_respond_to :soma 20 | end 21 | 22 | it 'deve ter um método para subtrair' do 23 | expect(@calculadora).must_respond_to :subtrai 24 | end 25 | end 26 | 27 | describe 'soma' do 28 | it 'deve ser igual a 2' do 29 | expect(@calculadora.soma(1, 1)).must_equal 2 30 | end 31 | end 32 | 33 | describe 'subtração' do 34 | it 'deve ser igual a 0' do 35 | expect(@calculadora.subtrai(1, 1)).must_equal 0 36 | end 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /testing/calc_spec2.rb: -------------------------------------------------------------------------------- 1 | require 'minitest/autorun' 2 | require_relative 'calc' 3 | 4 | describe Calculadora do 5 | before do 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | after do 10 | @calculadora = nil 11 | end 12 | 13 | describe 'média' do 14 | it 'deve ser igual a 2' do 15 | colecao = MiniTest::Mock.new 16 | colecao.expect :valores, [1, 2, 3] 17 | @calculadora.media(colecao) 18 | colecao.verify 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /testing/calc_spec3.rb: -------------------------------------------------------------------------------- 1 | require 'minitest/autorun' 2 | require_relative 'calc' 3 | 4 | describe Calculadora do 5 | before do 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | after do 10 | @calculadora = nil 11 | end 12 | 13 | describe 'soma maluca' do 14 | it 'deve ser igual a 3' do 15 | @calculadora.stub :soma, 3 do 16 | expect(@calculadora.soma(1, 1)).must_equal 3 17 | end 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /testing/calc_spec_reporters.rb: -------------------------------------------------------------------------------- 1 | require 'minitest/autorun' 2 | require_relative 'calc' 3 | 4 | require "minitest/reporters" 5 | Minitest::Reporters.use! 6 | 7 | describe Calculadora do 8 | before do 9 | @calculadora = Calculadora.new 10 | end 11 | 12 | after do 13 | @calculadora = nil 14 | end 15 | 16 | describe 'objeto' do 17 | it 'deve ser do tipo de Calculadora' do 18 | expect(@calculadora).must_be_kind_of Calculadora 19 | end 20 | 21 | it 'deve ter um método para somar' do 22 | expect(@calculadora).must_respond_to :soma 23 | end 24 | 25 | it 'deve ter um método para subtrair' do 26 | expect(@calculadora).must_respond_to :subtrai 27 | end 28 | end 29 | 30 | describe 'soma' do 31 | it 'deve ser igual a 2' do 32 | expect(@calculadora.soma(1, 1)).must_equal 2 33 | end 34 | end 35 | 36 | describe 'subtração' do 37 | it 'deve ser igual a 0' do 38 | expect(@calculadora.subtrai(1, 1)).must_equal 0 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /testing/calc_test.rb: -------------------------------------------------------------------------------- 1 | require 'test/unit' 2 | require_relative 'calc' 3 | 4 | class TesteCalculadora < Test::Unit::TestCase 5 | def setup 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | def test_adicao 10 | assert_equal(2, @calculadora.soma(1, 1), '1 + 1 = 2') 11 | end 12 | 13 | def test_subtracao 14 | assert_equal(0, @calculadora.subtrai(1, 1), '1 - 1 = 0') 15 | end 16 | 17 | def teardown 18 | @calculadora = nil 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /testing/calc_test2.rb: -------------------------------------------------------------------------------- 1 | require "test/unit" 2 | require_relative "calc" 3 | 4 | class TesteCalculadora < Test::Unit::TestCase 5 | def setup 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | def test_objeto 10 | assert_kind_of Calculadora, @calculadora 11 | assert_match /^\d$/, @calculadora.soma(1, 1).to_s 12 | assert_respond_to @calculadora, :soma 13 | assert_same @calculadora, @calculadora 14 | end 15 | 16 | def test_objetos 17 | assert_operator @calculadora.soma(1, 1), :>, @calculadora.soma(1, 0) 18 | end 19 | 20 | def test_adicao 21 | assert_equal 2, @calculadora.soma(1, 1), "1 + 1 = 2" 22 | end 23 | 24 | def test_subtracao 25 | assert_equal 0, @calculadora.subtrai(1, 1), "1 - 1 = 0" 26 | end 27 | 28 | def teardown 29 | @calculadora = nil 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /testing/calc_test_not.rb: -------------------------------------------------------------------------------- 1 | require 'test/unit' 2 | require_relative 'calc' 3 | 4 | class TesteCalculadora < Test::Unit::TestCase 5 | def setup 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | def test_adicao 10 | assert_equal(2, @calculadora.soma(1, 1), '1 + 1 = 2') 11 | end 12 | 13 | def test_subtracao 14 | notify('Começando o teste de subtração') 15 | assert_equal(0, @calculadora.subtrai(1, 1), '1 - 1 = 0') 16 | notify('Teste de subtração terminado') 17 | end 18 | 19 | def teardown 20 | @calculadora = nil 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /testing/calc_test_omit.rb: -------------------------------------------------------------------------------- 1 | require 'test/unit' 2 | require_relative 'calc' 3 | 4 | class TesteCalculadora < Test::Unit::TestCase 5 | def setup 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | def test_adicao 10 | assert_equal(2, @calculadora.soma(1, 1), '1 + 1 = 2') 11 | end 12 | 13 | def test_subtracao 14 | assert_equal(0, @calculadora.subtrai(1, 1), '1 - 1 = 0') 15 | end 16 | 17 | def test_raiz_quadrada 18 | omit('Fugi da escola, não sei fazer isso') 19 | assert_true(1 == 1) 20 | end 21 | 22 | def test_linux 23 | omit_unless('Só funciona no Linux', RUBY_PLATFORM.match?(/linux/i)) 24 | assert_true(Dir.exist?('/tmp')) 25 | end 26 | 27 | def test_tarde 28 | omit_if('Só roda à tarde', Time.now.hour >= 12) 29 | assert_true(Time.hour.hour >= 12) 30 | end 31 | 32 | def teardown 33 | @calculadora = nil 34 | end 35 | end 36 | 37 | -------------------------------------------------------------------------------- /testing/calc_test_pend.rb: -------------------------------------------------------------------------------- 1 | require 'test/unit' 2 | require_relative 'calc' 3 | 4 | class TesteCalculadora < Test::Unit::TestCase 5 | def setup 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | def test_adicao 10 | assert_equal(2, @calculadora.soma(1, 1), '1 + 1 = 2') 11 | end 12 | 13 | def test_subtracao 14 | assert_equal(0, @calculadora.subtrai(1, 1), '1 - 1 = 0') 15 | end 16 | 17 | def test_raiz_quadrada 18 | pend('Ainda não fizemos esse método') 19 | assert_equal(2, @calculadora.raiz_quadrada(4), '2 é raiz de 4') 20 | end 21 | 22 | def teardown 23 | @calculadora = nil 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /testing/carro.rb: -------------------------------------------------------------------------------- 1 | class Carro 2 | attr_reader :marca, :modelo, :tanque 3 | attr_accessor :cor 4 | @@qtde = 0 5 | 6 | def initialize(marca, modelo, cor, tanque) 7 | @marca = marca 8 | @modelo = modelo 9 | @cor = cor 10 | @tanque = tanque 11 | @@qtde += 1 12 | 13 | binding.irb 14 | end 15 | end 16 | 17 | Carro.new(:fiat, :pulse, :branco, 40) 18 | -------------------------------------------------------------------------------- /testing/minitest1.rb: -------------------------------------------------------------------------------- 1 | require 'minitest/autorun' 2 | require_relative 'calc' 3 | 4 | class TesteCalculadora < Minitest::Test 5 | def setup 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | def teardown 10 | @calculadora = nil 11 | end 12 | 13 | def test_objeto 14 | assert_kind_of Calculadora, @calculadora 15 | assert_match /^\d$/, @calculadora.soma(1, 1).to_s 16 | assert_respond_to @calculadora, :soma 17 | assert_same @calculadora, @calculadora 18 | end 19 | 20 | def test_objetos 21 | assert_operator @calculadora.soma(1, 1), :>, @calculadora.soma(1, 0) 22 | end 23 | 24 | def test_adicao 25 | assert_equal 2, @calculadora.soma(1, 1), "1 + 1 = 2" 26 | end 27 | 28 | def test_subtracao 29 | assert_equal 0, @calculadora.subtrai(1, 1), "1 - 1 = 0" 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /testing/spec/calc_spec.rb: -------------------------------------------------------------------------------- 1 | require "minitest/autorun" 2 | require_relative "../calc" 3 | 4 | describe Calculadora do 5 | before do 6 | @calculadora = Calculadora.new 7 | end 8 | 9 | after do 10 | @calculadora = nil 11 | end 12 | 13 | describe "objeto" do 14 | it "deve ser do tipo de Calculadora" do 15 | expect(@calculadora).must_be_kind_of Calculadora 16 | end 17 | 18 | it "deve ter um método para somar" do 19 | expect(@calculadora).must_respond_to :soma 20 | end 21 | 22 | it "deve ter um método para subtrair" do 23 | expect(@calculadora).must_respond_to :subtrai 24 | end 25 | end 26 | 27 | describe "soma" do 28 | it "deve ser igual a 2" do 29 | expect(@calculadora.soma(1, 1)).must_equal 2 30 | end 31 | end 32 | 33 | describe "subtração" do 34 | it "deve ser igual a 0" do 35 | expect(@calculadora.subtrai(1, 1)).must_equal 0 36 | end 37 | end 38 | 39 | describe "média" do 40 | it "deve ser igual a 2" do 41 | colecao = MiniTest::Mock.new 42 | colecao.expect :valores, [1, 2, 3] 43 | @calculadora.media(colecao) 44 | colecao.verify 45 | end 46 | end 47 | 48 | describe "soma maluca" do 49 | it "deve ser igual a 3" do 50 | @calculadora.stub :soma, 3 do 51 | expect(@calculadora.soma(1, 1)).must_equal 3 52 | end 53 | end 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /threads/bench1.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | require 'parallel' 3 | 4 | Benchmark.bm do |bm| 5 | bm.report do 6 | Parallel.map 1..20, in_threads: 4 do |nr| 7 | 5.times { sleep rand } 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /threads/bench2.rb: -------------------------------------------------------------------------------- 1 | require 'benchmark' 2 | require 'parallel' 3 | 4 | Benchmark.bm do |bm| 5 | bm.report('in_threads') do 6 | Parallel.map 1..20, in_threads: 4 do |nr| 7 | 5.times { sleep 0.5 } 8 | end 9 | end 10 | 11 | bm.report('in_processes') do 12 | Parallel.map 1..20, in_processes: 4 do |nr| 13 | 5.times { sleep 0.5 } 14 | end 15 | end 16 | 17 | bm.report('using threads') do 18 | threads = [] 19 | 20 | (1..20).each do |nr| 21 | threads << Thread.new do 22 | 5.times { sleep 0.5 } 23 | end 24 | end 25 | threads.each(&:join) 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /threads/cont.rb: -------------------------------------------------------------------------------- 1 | require 'continuation' 2 | 3 | def cria_continuation 4 | puts 'Criando a continuation e retornando ...' 5 | callcc { |it| return it } 6 | puts 'Ei, olha eu aqui de volta na continuation!' 7 | end 8 | 9 | puts 'Vou criar a continuation.' 10 | cont = cria_continuation() 11 | puts 'Verificando se existe ...' 12 | 13 | if cont 14 | puts 'Criada, vamos voltar para ela?' 15 | cont.call 16 | else 17 | puts 'Agora vamos embora.' 18 | end 19 | 20 | puts 'Terminei, tchau.' 21 | -------------------------------------------------------------------------------- /threads/fiber_names.rb: -------------------------------------------------------------------------------- 1 | # typed: false 2 | # frozen_string_literal: true 3 | require 'json' 4 | require 'net/http' 5 | require 'async/io' 6 | 7 | start = Time.now 8 | 9 | Thread.new do 10 | Fiber.set_scheduler Async::Scheduler.new 11 | 12 | %w[Joao Maria Eustaquio].each do |name| 13 | Fiber.schedule do 14 | current = Time.now 15 | uri = URI.parse("https://api.agify.io/") 16 | http = Net::HTTP.new(uri.host, uri.port) 17 | http.use_ssl = true 18 | json = JSON.parse(http.get("/?name=#{name}").body) 19 | age = json['age'] 20 | puts "%s: parece ter %s anos (levei %.3f segundos para calcular)\n" % [name, age, Time.now - current] 21 | end 22 | end 23 | end.join 24 | 25 | puts "Tempo total: #{Time.now - start}" 26 | -------------------------------------------------------------------------------- /threads/fibers1.rb: -------------------------------------------------------------------------------- 1 | enum1 = 3.times 2 | enum2 = %w(zero um dois).each 3 | puts enum1.class 4 | 5 | loop do 6 | puts enum1.next 7 | puts enum2.next 8 | end 9 | -------------------------------------------------------------------------------- /threads/fibers2.rb: -------------------------------------------------------------------------------- 1 | fib = Fiber.new do 2 | x, y = 0, 1 3 | 4 | loop do 5 | # envia o valor de y para resume 6 | # puts 'Indo para o resume' 7 | Fiber.yield y 8 | 9 | # volta aqui depois do resume 10 | # puts 'Voltei do resume' 11 | x, y = y, x + y 12 | end 13 | end 14 | 15 | 10.times { puts fib.resume } 16 | -------------------------------------------------------------------------------- /threads/fibers3.rb: -------------------------------------------------------------------------------- 1 | def create_fib 2 | x, y = 0, 1 3 | 4 | lambda do 5 | t, x, y = y, y, x + y 6 | return t 7 | end 8 | end 9 | 10 | proc = create_fib 11 | 10.times { puts proc.call } 12 | -------------------------------------------------------------------------------- /threads/fibers4.rb: -------------------------------------------------------------------------------- 1 | f2 = Fiber.new do |value| 2 | puts "Estou em f2 com #{value}, transferindo para onde vai resumir ..." 3 | Fiber.yield value + 40 4 | puts "Cheguei aqui?" 5 | end 6 | 7 | f1 = Fiber.new do 8 | puts "Comecei f1, transferindo para f2 ..." 9 | f2.resume 10 10 | end 11 | 12 | puts "Resumindo fiber 1: #{f1.resume}" 13 | -------------------------------------------------------------------------------- /threads/fibers5.rb: -------------------------------------------------------------------------------- 1 | require "fiber" 2 | 3 | f1 = Fiber.new do |other| 4 | puts "Comecei f1, transferindo para f2 ..." 5 | other.transfer Fiber.current, 10 6 | end 7 | 8 | f2 = Fiber.new do |caller, value| 9 | puts "Estou em f2, transferindo para f1 ..." 10 | caller.transfer value + 40 11 | puts "Cheguei aqui?" 12 | end 13 | 14 | puts "Resumindo fiber 1: #{f1.resume(f2)}" 15 | -------------------------------------------------------------------------------- /threads/fibers6.rb: -------------------------------------------------------------------------------- 1 | require "fiber" 2 | 3 | produtor = Fiber.new do |cons| 4 | 5.times do 5 | items = Array.new((rand * 5).to_i + 1, "oi!") 6 | puts "Produzidos #{items} ..." 7 | cons.transfer Fiber.current, items 8 | end 9 | end 10 | 11 | consumidor = Fiber.new do |prod, items| 12 | loop do 13 | puts "Consumidos #{items}" 14 | prod, items = prod.transfer 15 | end 16 | end 17 | 18 | produtor.resume consumidor 19 | -------------------------------------------------------------------------------- /threads/fibers7.rb: -------------------------------------------------------------------------------- 1 | str =< true 18 | p r2.take #=> true 19 | -------------------------------------------------------------------------------- /threads/rubyproftest.rb: -------------------------------------------------------------------------------- 1 | # typed: false 2 | # frozen_string_literal: true 3 | 4 | require 'date' 5 | 6 | 100_000.times do 7 | Date.parse(Date.today.to_s) 8 | end 9 | -------------------------------------------------------------------------------- /threads/thr1.rb: -------------------------------------------------------------------------------- 1 | thread = Thread.new do 2 | puts "Thread #{self.object_id} iniciada!" 3 | 4 | 5.times do |valor| 5 | puts valor 6 | sleep 1 7 | end 8 | end 9 | 10 | puts "Já criei a thread" 11 | thread.join 12 | -------------------------------------------------------------------------------- /threads/thr11.rb: -------------------------------------------------------------------------------- 1 | mutex = Mutex.new 2 | last_result = 1 3 | last_update = Time.now 4 | 5 | trap('SIGINT') do 6 | puts 'Saindo do programa ...' 7 | exit 8 | end 9 | 10 | Thread.new do 11 | loop do 12 | sleep 5 13 | puts 'Atualizando ...' 14 | 15 | mutex.synchronize do 16 | # fazendo alguma coisa demorada aqui 17 | puts 'Mutex sincronizado, vou fazer algo ...' 18 | sleep 10 19 | puts 'Terminei de fazer algo no mutex, vou liberar a sincronização' 20 | last_result += 1 21 | end 22 | 23 | last_update = Time.now 24 | puts 'Liberado o mutex.' 25 | end 26 | end 27 | 28 | loop do 29 | puts 'Aperte ENTER para ver o resultado:' 30 | gets 31 | 32 | # tenta adquirir o lock, se não estiver entre o synchronize e o end 33 | # lá em cima 34 | if mutex.try_lock 35 | begin 36 | puts "Resultado atualizado #{(Time.now - last_update).to_i} segundos atrás." 37 | ensure 38 | mutex.unlock 39 | end 40 | # se não conseguiu, é que está lá em cima, processando entre 41 | # o synchronize e o end! 42 | else 43 | puts "Sendo atualizado, resultado anterior gerado #{(Time.now - last_update).to_i} segundos atrás" 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /threads/thr2.rb: -------------------------------------------------------------------------------- 1 | thread = Thread.new do 2 | puts "Thread #{self.object_id} iniciada!" 3 | 4 | 5.times do |valor| 5 | puts valor 6 | sleep 1 7 | end 8 | end 9 | 10 | puts "Já criei a thread" 11 | thread.join(3) 12 | -------------------------------------------------------------------------------- /threads/thr3.rb: -------------------------------------------------------------------------------- 1 | proc = Proc.new do |parametro| 2 | parametro.times do |valor| 3 | print "[#{valor + 1}/#{parametro}]" 4 | sleep 0.5 5 | end 6 | end 7 | 8 | thread = nil 9 | 5.times do |valor| 10 | thread = Thread.new(valor, &proc) 11 | end 12 | 13 | thread.join 14 | puts "Terminado!" 15 | -------------------------------------------------------------------------------- /threads/thr4.rb: -------------------------------------------------------------------------------- 1 | maior, menor = 0, 0 2 | log = 0 3 | 4 | t1 = Thread.new do 5 | loop do 6 | maior += 1 7 | menor -= 1 8 | end 9 | end 10 | 11 | t2 = Thread.new do 12 | loop do 13 | log = menor + maior 14 | end 15 | end 16 | 17 | sleep 3 18 | puts "log vale #{log}" 19 | -------------------------------------------------------------------------------- /threads/thr5.rb: -------------------------------------------------------------------------------- 1 | maior, menor = 0, 0 2 | log = 0 3 | 4 | mutex = Mutex.new 5 | t1 = Thread.new do 6 | loop do 7 | mutex.synchronize do 8 | maior += 1 9 | menor -= 1 10 | end 11 | end 12 | end 13 | 14 | t2 = Thread.new do 15 | loop do 16 | mutex.synchronize do 17 | log = menor + maior 18 | end 19 | end 20 | end 21 | 22 | sleep 3 23 | puts "log vale #{log}" 24 | -------------------------------------------------------------------------------- /threads/thr6.rb: -------------------------------------------------------------------------------- 1 | require "monitor" 2 | 3 | maior, menor = 0, 0 4 | log = 0 5 | mutex = Monitor.new 6 | t1 = Thread.new do 7 | loop do 8 | mutex.synchronize do 9 | maior += 1 10 | menor -= 1 11 | end 12 | end 13 | end 14 | 15 | t2 = Thread.new do 16 | loop do 17 | mutex.synchronize do 18 | log = menor + maior 19 | end 20 | end 21 | end 22 | 23 | sleep 3 24 | puts "log vale #{log}" 25 | -------------------------------------------------------------------------------- /threads/thr7.rb: -------------------------------------------------------------------------------- 1 | require "monitor" 2 | 3 | class Contador1 4 | attr_reader :valor 5 | include MonitorMixin 6 | 7 | def initialize 8 | @valor = 0 9 | super 10 | end 11 | 12 | def incrementa 13 | synchronize do 14 | @valor = valor + 1 15 | end 16 | end 17 | end 18 | 19 | class Contador2 20 | attr_reader :valor 21 | 22 | def initialize 23 | @valor = 0 24 | end 25 | 26 | def incrementa 27 | @valor = valor + 1 28 | end 29 | end 30 | 31 | c1 = Contador1.new 32 | c2 = Contador2.new 33 | c2.extend(MonitorMixin) 34 | 35 | t1 = Thread.new { 100_000.times { c1.incrementa } } 36 | t2 = Thread.new { 100_000.times { c1.incrementa } } 37 | 38 | t1.join 39 | t2.join 40 | puts c1.valor 41 | 42 | t3 = Thread.new { 100_000.times { c2.synchronize { c2.incrementa } } } 43 | t4 = Thread.new { 100_000.times { c2.synchronize { c2.incrementa } } } 44 | 45 | t3.join 46 | t4.join 47 | puts c2.valor 48 | -------------------------------------------------------------------------------- /threads/thr71.rb: -------------------------------------------------------------------------------- 1 | require 'monitor' 2 | 3 | class Contador1 4 | attr_reader :valor 5 | include MonitorMixin 6 | 7 | def initialize 8 | @valor = 0 9 | super 10 | end 11 | 12 | def incrementa 13 | synchronize do 14 | @valor = valor + 1 15 | end 16 | end 17 | end 18 | 19 | c1 = Contador1.new 20 | 21 | t1 = Thread.new { 100_000.times { c1.incrementa } } 22 | t2 = Thread.new { 100_000.times { c1.incrementa } } 23 | 24 | t1.join 25 | t2.join 26 | puts c1.valor 27 | -------------------------------------------------------------------------------- /threads/thr72.rb: -------------------------------------------------------------------------------- 1 | require 'monitor' 2 | 3 | class Contador2 4 | attr_reader :valor 5 | 6 | def initialize 7 | @valor = 0 8 | end 9 | 10 | def incrementa 11 | @valor = valor + 1 12 | end 13 | end 14 | 15 | c2 = Contador2.new 16 | c2.extend(MonitorMixin) 17 | 18 | t3 = Thread.new { 100_000.times { c2.synchronize { c2.incrementa } } } 19 | t4 = Thread.new { 100_000.times { c2.synchronize { c2.incrementa } } } 20 | 21 | t3.join 22 | t4.join 23 | puts c2.valor 24 | -------------------------------------------------------------------------------- /threads/thr8.rb: -------------------------------------------------------------------------------- 1 | require "thread" 2 | 3 | items = [] 4 | lock = Mutex.new 5 | cond = ConditionVariable.new 6 | limit = 0 7 | 8 | produtor = Thread.new do 9 | loop do 10 | lock.synchronize do 11 | qtde = rand(50) 12 | next if qtde == 0 13 | 14 | puts "produzindo #{qtde} item(s)" 15 | items = Array.new(qtde,"item") 16 | cond.wait(lock) 17 | puts "consumo efetuado!" 18 | puts "-" * 25 19 | limit += 1 20 | end 21 | break if limit > 5 22 | end 23 | end 24 | 25 | consumidor = Thread.new do 26 | loop do 27 | lock.synchronize do 28 | if items.length>0 29 | puts "consumindo #{items.length} item(s)" 30 | items = [] 31 | end 32 | cond.signal 33 | end 34 | end 35 | end 36 | produtor.join 37 | -------------------------------------------------------------------------------- /threads/thr9.rb: -------------------------------------------------------------------------------- 1 | require "thread" 2 | 3 | queue = Queue.new 4 | limit = 0 5 | 6 | produtor = Thread.new do 7 | loop do 8 | qtde = rand(50) 9 | next if qtde.zero? 10 | 11 | limit += 1 12 | 13 | if limit > 5 14 | queue.enq :END_OF_WORK 15 | break 16 | end 17 | 18 | puts "produzindo #{qtde} item(s)" 19 | queue.enq Array.new(qtde, 'item') 20 | sleep 1 21 | end 22 | end 23 | 24 | consumidor = Thread.new do 25 | loop do 26 | obj = queue.deq 27 | break if obj == :END_OF_WORK 28 | 29 | print "consumindo #{obj.size} item(s)\n" 30 | end 31 | end 32 | 33 | produtor.join 34 | consumidor.join 35 | --------------------------------------------------------------------------------