SlideShare a Scribd company logo
1 of 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!

More Related Content

What's hot

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
 

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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 to 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 to 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
 

More from 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
 

More from 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.
 

Recently uploaded

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

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!

Editor's Notes

  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