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

PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
Radek Benkel
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
Jochen Rau
 
Elixir cheatsheet
Elixir cheatsheetElixir cheatsheet
Elixir cheatsheet
Héla Ben Khalfallah
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
gsterndale
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
Sanketkumar Biswas
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会
Yusuke Ando
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
Sérgio Rafael Siqueira
 
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 BioPerl
Jason Stajich
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
David 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 Version
Ian Barber
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
Ahmed Swilam
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Ryan McGeary
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6
Andrew Shitov
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
lichtkind
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
niklal
 

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
 
Java script
Java scriptJava script
Java script
Jay Patel
 

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 Erlang
Sean Cribbs
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
Justin 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 2011
Tudor 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
 
Php functions
Php functionsPhp functions
Php functions
JIGAR MAKHIJA
 
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 mongers
brian 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 Functionally
Sean Cribbs
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
Simon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
Simon Proctor
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
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
Jeremy Kendall
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
Michelangelo van Dam
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
kamaelian
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
Alena Holligan
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
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 demystified
Tom Crinson
 
Crystal Agile
Crystal AgileCrystal Agile
Crystal Agile
Tom 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 Ruby
Tom Crinson
 
Itty bittypresentation lrug
Itty bittypresentation lrugItty bittypresentation lrug
Itty bittypresentation lrug
Tom Crinson
 
Object Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLIDObject Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLID
Tom 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

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 

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