SlideShare una empresa de Scribd logo
1 de 28
HIDDEN TREASURES
       of
      RUBY


  @MrJaba - iprug - 6th Dec 2011
Whistlestop tour through the lesser
known/obscure features of Ruby
Ruby has a
   HUGE
standard library
Have you heard of?
       Struct

       OpenStruct

       OptionParser

       Abbrev

       Benchmark

       Find

       English
Did you know about?
       String#squeeze

       String#count

       String#tr

       Kernel#Array

       Kernel#trace_var
This is just for FUN
Core Ruby
STRING
                      #squeeze


 “Uh oh the cat sat on the keeeeeeeeeee”.squeeze
=>
“Uh oh the cat sat on the ke”

 “oh craaaapppp my aaappp keys are bloody
           broken”.squeeze(“ap”)
=>
 “oh crap my ap keys are bloody broken”
STRING
          #count

“FINISHED FILES ARE THE RE-
SULT OF YEARS OF SCIENTIF-
IC STUDY COMBINED WITH
THE EXPERIENCE OF YEARS.”

 How many F’s are there?
STRING
                           #count


“FINISHED FILES ARE THE RE-
SULT OF YEARS OF SCIENTIF-
IC STUDY COMBINED WITH
THE EXPERIENCE OF YEARS.”.count(“F”)

=>
6
STRING
                      #count


“how many woods would a wood chuck chuck if a
wood chuck could chuck wood?”.count(“a-z”, “^u”)

=>
52
“DYTSMH”
.tr(“DYTSMH”, “STRING”)

   “STRING”
     .tr(“R-T”, “F”)

   “FFFING”
KERNEL
                    #Array

                       yesthat’sacapitalletter


     Array(1..3) + Array(args[:thing])
=
 [1,2,3, “Thing”]
thing.to_a
=
NoMethodError: undefined method `to_a' for
thing:String
KERNEL
                                   #at_exit


     at_exit { p ObjectSpace.count_objects }
=
{:TOTAL=31479, :FREE=4687, :T_OBJECT=1442, :T_CLASS=859, :T_MODULE=32, :T_FLOAT=7,
:T_STRING=18190, :T_REGEXP=168, :T_ARRAY=3657, :T_HASH=134, :T_STRUCT=1, :T_BIGNUM=2,
:T_FILE=6, :T_DATA=1210, :T_MATCH=100, :T_COMPLEX=1, :T_NODE=949, :T_ICLASS=34}



at_exit {
 loop do
   p “unkillable code!”
 end }
KERNEL
                                                         #set_trace_func
class Cheese
 def eat
   p “om nom nom”
 end
end

set_trace_func proc {|event, file, line, id, binding, classname|
  p “#{event}, #{file}, #{line}, #{id}, #{binding}, #{classname}”
}

=
c-return, cheese.rb, 9, set_trace_func, #Binding:0x007fe11b84e488, Kernel
line, cheese.rb, 11, , #Binding:0x007fe11b84e1e0, 
c-call, cheese.rb, 11, new, #Binding:0x007fe11b84dfb0, Class
c-call, cheese.rb, 11, initialize, #Binding:0x007fe11b84dc90, BasicObject
c-return, cheese.rb, 11, initialize, #Binding:0x007fe11b84da38, BasicObject
c-return, cheese.rb, 11, new, #Binding:0x007fe11b84d808, Class
line, cheese.rb, 12, , #Binding:0x007fe11b84d5d8, 
call, cheese.rb, 2, eat, #Binding:0x007fe11b84d3a8, Cheese
line, cheese.rb, 3, eat, #Binding:0x007fe11b84d150, Cheese
c-call, cheese.rb, 3, p, #Binding:0x007fe11b84cef8, Kernel
c-call, cheese.rb, 3, inspect, #Binding:0x007fe11b84ccc8, String
c-return, cheese.rb, 3, inspect, #Binding:0x007fe11b84ca48, String
om nom nom
c-return, cheese.rb, 3, p, #Binding:0x007fe11b84c7f0, Kernel
return, cheese.rb, 4, eat, #Binding:0x007fe11b84c5c0, Cheese
Struct

Point = Struct.new :x, :y do
 def distance(point)
  Math.sqrt((point.x - self.x) ** 2 +
  (point.y - self.y) ** 2)
 end
end
Why?   Struct

Quickly define a class with a few known fields

            Automatic Hash key

Mitigate risk of spelling errors on field names
Ruby
STANDARD
 LIBRARY
113 Packages
OptionParser
                                 require ‘optparse’
options = {}
parser = OptionParser.new

parser.on(-i, --ipswich, description of IP) {|val| options[:ipswich] = val }
parser.on(-r=ARG, --ruby, Mandatory Argument) {|val| options[:ruby] = val }
parser.on(-u=[ARG], --user, Optional Argument) {|val| options[:user] = val }
parser.on(-g=ARG, --group, Integer, Type cast Argument) {|val| options[:group] = val }

unmatched = parser.parse(ARGV)

puts parser.to_s

puts options are #{options.inspect}
puts unmatched are #{unmatched.inspect}
Abbrev
                   require ‘abbrev’

 Abbrev::abbrev(['Whatever'])

{Whateve=Whatever, Whatev=Whateve
Whate=Whatever, What=Whatever,
Wha=Whatever, Wh=Whatever,
W=Whatever, Whatever=Whatever}


        Thereisno“whatevs”inthere!
Benchmark
                          require ‘benchmark’

   puts Benchmark.measure { calculate_meaning_of_life }
   =
   0.42 0.42 0.42 ( 4.2)

                                            ElapsedRealTime
UserCPU              Sum
              SystemCPU
   Benchmark.bmbm do |x|
    x.report(sort!) { array.dup.sort! }
    x.report(sort) { array.dup.sort }
   end
   =
          user   system  total   real
   sort! 12.959000 0.010000 12.969000 ( 13.793000)
   sort 12.007000 0.000000 12.007000 ( 12.791000)
English
                                  require ‘English’
$ERROR_INFO            $!                  $DEFAULT_OUTPUT             $

$ERROR_POSITION             $@             $DEFAULT_INPUT             $

$FS           $;                           $PID             $$

$FIELD_SEPARATOR            $;             $PROCESS_ID            $$

$OFS              $,                       $CHILD_STATUS              $?

$OUTPUT_FIELD_SEPARATOR $,                 $LAST_MATCH_INFO                $~

$RS               $/                       $IGNORECASE            $=

$INPUT_RECORD_SEPARATOR $/                 $ARGV             $*

$ORS              $                       $MATCH                $

$OUTPUT_RECORD_SEPARATOR $                $PREMATCH              $`

$INPUT_LINE_NUMBER           $.            $POSTMATCH             $'

$NR               $.                       $LAST_PAREN_MATCH               $+

$LAST_READ_LINE         $_
Find
               require ‘find’

Find.find(“/Users/ET”) do |path|
 puts path
 Find.prune if path =~ /hell/
end
=                                Geddit?
/Users/ET/phone
/Users/ET/home
Profiler__
                                require ‘profiler’

Profiler__::start_profile
complicated_method_call
Profiler__::stop_profile
Profiler__::print_profile($stdout)



 % cumulative   self      self   total
time seconds    seconds calls ms/call ms/call name
0.00  0.00      0.00    1   0.00   0.00 Integer#times
0.00  0.00      0.00    1   0.00   0.00 Object#complicated_method_call
0.00  0.01      0.00    1   0.00 10.00 #toplevel
RSS
                       require ‘rss/2.0’



response = open(http://feeds.feedburner.com/MrjabasAdventures).read
rss = RSS::Parser.parse(response, false)
rss.items.each do |item|
 p item.title
end
MiniTest
          require ‘minitest/autorun’
        describe Cheese do
         before do
          @cheddar = Cheese.new(“cheddar”)
         end

         describe when enquiring about smelliness do
          it must respond with a stink factor do
            @cheddar.smelliness?.must_equal 0.9
          end
         end
        end




                Provides:
Specs Mocking Stubbing Runners Benchmarks
Thank you to
everyone involved in
       Ruby!

Más contenido relacionado

La actualidad más candente

Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with ExtbaseJochen Rau
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会Yusuke Ando
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsSunil Kumar Gunasekaran
 
Comparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerlComparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerlJason Stajich
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionIan Barber
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP ArraysAhmed Swilam
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6Andrew Shitov
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Contextlichtkind
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 

La actualidad más candente (20)

PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
Elixir cheatsheet
Elixir cheatsheetElixir cheatsheet
Elixir cheatsheet
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
C99
C99C99
C99
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Comparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerlComparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerl
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 

Destacado

Arqu hardware 02 - sockets (63170)
Arqu hardware   02 - sockets (63170)Arqu hardware   02 - sockets (63170)
Arqu hardware 02 - sockets (63170)paola
 
Survey plan-updated
Survey plan-updatedSurvey plan-updated
Survey plan-updatedjryalo
 
Arqu hardware 02 - sockets (63170)
Arqu hardware   02 - sockets (63170)Arqu hardware   02 - sockets (63170)
Arqu hardware 02 - sockets (63170)paola
 
Arqu hardware 11 - fuentes de poder (63170)
Arqu hardware   11 - fuentes de poder (63170)Arqu hardware   11 - fuentes de poder (63170)
Arqu hardware 11 - fuentes de poder (63170)paola
 
Javascript Basics for Advertisers
Javascript Basics for AdvertisersJavascript Basics for Advertisers
Javascript Basics for AdvertisersTom Crinson
 

Destacado (7)

Arqu hardware 02 - sockets (63170)
Arqu hardware   02 - sockets (63170)Arqu hardware   02 - sockets (63170)
Arqu hardware 02 - sockets (63170)
 
Survey plan-updated
Survey plan-updatedSurvey plan-updated
Survey plan-updated
 
Arqu hardware 02 - sockets (63170)
Arqu hardware   02 - sockets (63170)Arqu hardware   02 - sockets (63170)
Arqu hardware 02 - sockets (63170)
 
Arqu hardware 11 - fuentes de poder (63170)
Arqu hardware   11 - fuentes de poder (63170)Arqu hardware   11 - fuentes de poder (63170)
Arqu hardware 11 - fuentes de poder (63170)
 
Project 9
Project 9Project 9
Project 9
 
Javascript Basics for Advertisers
Javascript Basics for AdvertisersJavascript Basics for Advertisers
Javascript Basics for Advertisers
 
Java script
Java scriptJava script
Java script
 

Similar a Hidden treasures of Ruby

Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangSean Cribbs
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Tudor Girba
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Workhorse Computing
 
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...adrianoalmeida7
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongersbrian d foy
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Round PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallyRound PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallySean Cribbs
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodJeremy Kendall
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parserkamaelian
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 

Similar a Hidden treasures of Ruby (20)

Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
Php functions
Php functionsPhp functions
Php functions
 
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...
Cypher inside out: Como a linguagem de pesquisas em grafo do Neo4j foi constr...
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Round PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallyRound PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing Functionally
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 

Más de Tom Crinson

Destructuring demystified
Destructuring demystifiedDestructuring demystified
Destructuring demystifiedTom Crinson
 
A few questions on MongoDB
A few questions on MongoDBA few questions on MongoDB
A few questions on MongoDBTom Crinson
 
Higher Order Ruby
Higher Order RubyHigher Order Ruby
Higher Order RubyTom Crinson
 
Itty bittypresentation lrug
Itty bittypresentation lrugItty bittypresentation lrug
Itty bittypresentation lrugTom Crinson
 
Object Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLIDObject Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLIDTom Crinson
 
Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Tom Crinson
 

Más de Tom Crinson (7)

Destructuring demystified
Destructuring demystifiedDestructuring demystified
Destructuring demystified
 
Crystal Agile
Crystal AgileCrystal Agile
Crystal Agile
 
A few questions on MongoDB
A few questions on MongoDBA few questions on MongoDB
A few questions on MongoDB
 
Higher Order Ruby
Higher Order RubyHigher Order Ruby
Higher Order Ruby
 
Itty bittypresentation lrug
Itty bittypresentation lrugItty bittypresentation lrug
Itty bittypresentation lrug
 
Object Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLIDObject Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLID
 
Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it.
 

Último

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Último (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Hidden treasures of Ruby

  • 1. HIDDEN TREASURES of RUBY @MrJaba - iprug - 6th Dec 2011
  • 2. Whistlestop tour through the lesser known/obscure features of Ruby
  • 3. Ruby has a HUGE standard library
  • 4. Have you heard of? Struct OpenStruct OptionParser Abbrev Benchmark Find English
  • 5. Did you know about? String#squeeze String#count String#tr Kernel#Array Kernel#trace_var
  • 6. This is just for FUN
  • 8. STRING #squeeze “Uh oh the cat sat on the keeeeeeeeeee”.squeeze => “Uh oh the cat sat on the ke” “oh craaaapppp my aaappp keys are bloody broken”.squeeze(“ap”) => “oh crap my ap keys are bloody broken”
  • 9. STRING #count “FINISHED FILES ARE THE RE- SULT OF YEARS OF SCIENTIF- IC STUDY COMBINED WITH THE EXPERIENCE OF YEARS.” How many F’s are there?
  • 10. STRING #count “FINISHED FILES ARE THE RE- SULT OF YEARS OF SCIENTIF- IC STUDY COMBINED WITH THE EXPERIENCE OF YEARS.”.count(“F”) => 6
  • 11. STRING #count “how many woods would a wood chuck chuck if a wood chuck could chuck wood?”.count(“a-z”, “^u”) => 52
  • 12. “DYTSMH” .tr(“DYTSMH”, “STRING”) “STRING” .tr(“R-T”, “F”) “FFFING”
  • 13. KERNEL #Array yesthat’sacapitalletter Array(1..3) + Array(args[:thing]) = [1,2,3, “Thing”] thing.to_a = NoMethodError: undefined method `to_a' for thing:String
  • 14. KERNEL #at_exit at_exit { p ObjectSpace.count_objects } = {:TOTAL=31479, :FREE=4687, :T_OBJECT=1442, :T_CLASS=859, :T_MODULE=32, :T_FLOAT=7, :T_STRING=18190, :T_REGEXP=168, :T_ARRAY=3657, :T_HASH=134, :T_STRUCT=1, :T_BIGNUM=2, :T_FILE=6, :T_DATA=1210, :T_MATCH=100, :T_COMPLEX=1, :T_NODE=949, :T_ICLASS=34} at_exit { loop do p “unkillable code!” end }
  • 15. KERNEL #set_trace_func class Cheese def eat p “om nom nom” end end set_trace_func proc {|event, file, line, id, binding, classname| p “#{event}, #{file}, #{line}, #{id}, #{binding}, #{classname}” } = c-return, cheese.rb, 9, set_trace_func, #Binding:0x007fe11b84e488, Kernel line, cheese.rb, 11, , #Binding:0x007fe11b84e1e0, c-call, cheese.rb, 11, new, #Binding:0x007fe11b84dfb0, Class c-call, cheese.rb, 11, initialize, #Binding:0x007fe11b84dc90, BasicObject c-return, cheese.rb, 11, initialize, #Binding:0x007fe11b84da38, BasicObject c-return, cheese.rb, 11, new, #Binding:0x007fe11b84d808, Class line, cheese.rb, 12, , #Binding:0x007fe11b84d5d8, call, cheese.rb, 2, eat, #Binding:0x007fe11b84d3a8, Cheese line, cheese.rb, 3, eat, #Binding:0x007fe11b84d150, Cheese c-call, cheese.rb, 3, p, #Binding:0x007fe11b84cef8, Kernel c-call, cheese.rb, 3, inspect, #Binding:0x007fe11b84ccc8, String c-return, cheese.rb, 3, inspect, #Binding:0x007fe11b84ca48, String om nom nom c-return, cheese.rb, 3, p, #Binding:0x007fe11b84c7f0, Kernel return, cheese.rb, 4, eat, #Binding:0x007fe11b84c5c0, Cheese
  • 16. Struct Point = Struct.new :x, :y do def distance(point) Math.sqrt((point.x - self.x) ** 2 + (point.y - self.y) ** 2) end end
  • 17. Why? Struct Quickly define a class with a few known fields Automatic Hash key Mitigate risk of spelling errors on field names
  • 20. OptionParser require ‘optparse’ options = {} parser = OptionParser.new parser.on(-i, --ipswich, description of IP) {|val| options[:ipswich] = val } parser.on(-r=ARG, --ruby, Mandatory Argument) {|val| options[:ruby] = val } parser.on(-u=[ARG], --user, Optional Argument) {|val| options[:user] = val } parser.on(-g=ARG, --group, Integer, Type cast Argument) {|val| options[:group] = val } unmatched = parser.parse(ARGV) puts parser.to_s puts options are #{options.inspect} puts unmatched are #{unmatched.inspect}
  • 21. Abbrev require ‘abbrev’ Abbrev::abbrev(['Whatever']) {Whateve=Whatever, Whatev=Whateve Whate=Whatever, What=Whatever, Wha=Whatever, Wh=Whatever, W=Whatever, Whatever=Whatever} Thereisno“whatevs”inthere!
  • 22. Benchmark require ‘benchmark’ puts Benchmark.measure { calculate_meaning_of_life } = 0.42 0.42 0.42 ( 4.2) ElapsedRealTime UserCPU Sum SystemCPU Benchmark.bmbm do |x| x.report(sort!) { array.dup.sort! } x.report(sort) { array.dup.sort } end = user system total real sort! 12.959000 0.010000 12.969000 ( 13.793000) sort 12.007000 0.000000 12.007000 ( 12.791000)
  • 23. English require ‘English’ $ERROR_INFO $! $DEFAULT_OUTPUT $ $ERROR_POSITION $@ $DEFAULT_INPUT $ $FS $; $PID $$ $FIELD_SEPARATOR $; $PROCESS_ID $$ $OFS $, $CHILD_STATUS $? $OUTPUT_FIELD_SEPARATOR $, $LAST_MATCH_INFO $~ $RS $/ $IGNORECASE $= $INPUT_RECORD_SEPARATOR $/ $ARGV $* $ORS $ $MATCH $ $OUTPUT_RECORD_SEPARATOR $ $PREMATCH $` $INPUT_LINE_NUMBER $. $POSTMATCH $' $NR $. $LAST_PAREN_MATCH $+ $LAST_READ_LINE $_
  • 24. Find require ‘find’ Find.find(“/Users/ET”) do |path| puts path Find.prune if path =~ /hell/ end = Geddit? /Users/ET/phone /Users/ET/home
  • 25. Profiler__ require ‘profiler’ Profiler__::start_profile complicated_method_call Profiler__::stop_profile Profiler__::print_profile($stdout) % cumulative self self total time seconds seconds calls ms/call ms/call name 0.00 0.00 0.00 1 0.00 0.00 Integer#times 0.00 0.00 0.00 1 0.00 0.00 Object#complicated_method_call 0.00 0.01 0.00 1 0.00 10.00 #toplevel
  • 26. RSS require ‘rss/2.0’ response = open(http://feeds.feedburner.com/MrjabasAdventures).read rss = RSS::Parser.parse(response, false) rss.items.each do |item| p item.title end
  • 27. MiniTest require ‘minitest/autorun’ describe Cheese do before do @cheddar = Cheese.new(“cheddar”) end describe when enquiring about smelliness do it must respond with a stink factor do @cheddar.smelliness?.must_equal 0.9 end end end Provides: Specs Mocking Stubbing Runners Benchmarks
  • 28. Thank you to everyone involved in Ruby!

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n