SlideShare uma empresa 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!

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante 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
 

Semelhante 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
 

Mais 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
 

Mais 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

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Último (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

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 do 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