Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Hidden treasures of Ruby

1,465 views

Published on

Ruby is amazing. It has a huge standard library and a core choc full of weird and wonderful things. In this talk, given at the Ipswich Ruby User Group, I give a whimsical nonstop tour through some of the more obscure parts of Ruby.

  • Login to see the comments

Hidden treasures of Ruby

  1. 1. HIDDEN TREASURES of RUBY @MrJaba - iprug - 6th Dec 2011
  2. 2. Whistlestop tour through the lesserknown/obscure features of Ruby
  3. 3. Ruby has a HUGEstandard library
  4. 4. Have you heard of? Struct OpenStruct OptionParser Abbrev Benchmark Find English
  5. 5. Did you know about? String#squeeze String#count String#tr Kernel#Array Kernel#trace_var
  6. 6. This is just for FUN
  7. 7. Core Ruby
  8. 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. 9. STRING #count“FINISHED FILES ARE THE RE-SULT OF YEARS OF SCIENTIF-IC STUDY COMBINED WITHTHE EXPERIENCE OF YEARS.” How many F’s are there?
  10. 10. STRING #count“FINISHED FILES ARE THE RE-SULT OF YEARS OF SCIENTIF-IC STUDY COMBINED WITHTHE EXPERIENCE OF YEARS.”.count(“F”)=>6
  11. 11. STRING #count“how many woods would a wood chuck chuck if awood chuck could chuck wood?”.count(“a-z”, “^u”)=>52
  12. 12. “DYTSMH”.tr(“DYTSMH”, “STRING”) “STRING” .tr(“R-T”, “F”) “FFFING”
  13. 13. KERNEL #Array yesthat’sacapitalletter Array(1..3) + Array(args[:thing])= [1,2,3, “Thing”]thing.to_a=NoMethodError: undefined method `to_a forthing:String
  14. 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. 15. KERNEL #set_trace_funcclass Cheese def eat p “om nom nom” endendset_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, Kernelline, cheese.rb, 11, , #Binding:0x007fe11b84e1e0, c-call, cheese.rb, 11, new, #Binding:0x007fe11b84dfb0, Classc-call, cheese.rb, 11, initialize, #Binding:0x007fe11b84dc90, BasicObjectc-return, cheese.rb, 11, initialize, #Binding:0x007fe11b84da38, BasicObjectc-return, cheese.rb, 11, new, #Binding:0x007fe11b84d808, Classline, cheese.rb, 12, , #Binding:0x007fe11b84d5d8, call, cheese.rb, 2, eat, #Binding:0x007fe11b84d3a8, Cheeseline, cheese.rb, 3, eat, #Binding:0x007fe11b84d150, Cheesec-call, cheese.rb, 3, p, #Binding:0x007fe11b84cef8, Kernelc-call, cheese.rb, 3, inspect, #Binding:0x007fe11b84ccc8, Stringc-return, cheese.rb, 3, inspect, #Binding:0x007fe11b84ca48, Stringom nom nomc-return, cheese.rb, 3, p, #Binding:0x007fe11b84c7f0, Kernelreturn, cheese.rb, 4, eat, #Binding:0x007fe11b84c5c0, Cheese
  16. 16. StructPoint = Struct.new :x, :y do def distance(point) Math.sqrt((point.x - self.x) ** 2 + (point.y - self.y) ** 2) endend
  17. 17. Why? StructQuickly define a class with a few known fields Automatic Hash keyMitigate risk of spelling errors on field names
  18. 18. RubySTANDARD LIBRARY
  19. 19. 113 Packages
  20. 20. OptionParser require ‘optparse’options = {}parser = OptionParser.newparser.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_sputs options are #{options.inspect}puts unmatched are #{unmatched.inspect}
  21. 21. Abbrev require ‘abbrev’ Abbrev::abbrev([Whatever]){Whateve=Whatever, Whatev=WhateveWhate=Whatever, What=Whatever,Wha=Whatever, Wh=Whatever,W=Whatever, Whatever=Whatever} Thereisno“whatevs”inthere!
  22. 22. Benchmark require ‘benchmark’ puts Benchmark.measure { calculate_meaning_of_life } = 0.42 0.42 0.42 ( 4.2) ElapsedRealTimeUserCPU 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. 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. 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. 25. Profiler__ require ‘profiler’Profiler__::start_profilecomplicated_method_callProfiler__::stop_profileProfiler__::print_profile($stdout) % cumulative self self totaltime seconds seconds calls ms/call ms/call name0.00 0.00 0.00 1 0.00 0.00 Integer#times0.00 0.00 0.00 1 0.00 0.00 Object#complicated_method_call0.00 0.01 0.00 1 0.00 10.00 #toplevel
  26. 26. RSS require ‘rss/2.0’response = open(http://feeds.feedburner.com/MrjabasAdventures).readrss = RSS::Parser.parse(response, false)rss.items.each do |item| p item.titleend
  27. 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. 28. Thank you toeveryone involved in Ruby!

×