Friday, November 14, 2014

Ruby pearls and gems for your daily routine coding tasks

This is a list of ruby pearls and gems, that help me in my daily routine coding tasks.




1. Retain only unique elements in an array:

  1. a = [1, 1, 2, 3, 4, 4, 5]  
  2.   
  3. a = a.uniq # => [1, 2, 3, 4, 5]  

2. Command line options parsing:

  1. require 'optparse'  
  2. class Optparser  
  3.   
  4. def self.parse(args)  
  5.   options = {}  
  6.   OptionParser.new do |opts|  
  7.     opts.banner = "Usage: example.rb [options]"  
  8.   
  9.     opts.on("-v""--[no-]verbose""Run verbosely"do |v|  
  10.      options[:verbose] = v  
  11.     end  
  12.   
  13.    opts.on("-o""--require OUTPUTDIR""Output directory"do |o|  
  14.      options[:output_dir] = o  
  15.    end  
  16.   
  17.    options[:source_dir] = []  
  18.      opts.on("-s""--require SOURCEDIR""Source directory"do |s|  
  19.      options[:source_dir] << s  
  20.    end  
  21.   
  22.    end.parse!  
  23.   
  24.    options  
  25.   end  
  26. end  
  27.   
  28. options = Optparser.parse(ARGV) #pp options  When executed with -h, this script will automatically show the options and exit.    

3. Delete a key-value pair in the hash map, where the key matches certain condition:

  1. hashMap.delete_if {|key, value| key == "someString" }  

Certainly, you can use regular expression based matching for the condition or a custom function, say, on the 'key' value.


4. Interacting with mysql. I use mysql2 gem. Check out the documentation, it is pretty self-evident.

5. Working with Apache SOLR: rsolr and rsolr-ext are invaluable here:

  1. require 'rsolr'  
  2. require 'rsolr-ext'  
  3. solrServer = RSolr::Ext.connect :url => $solrServerUrl:read_timeout => $read_timeout:open_timeout => $open_timeout  
  4.   
  5. doc = {field1=>"value1""field2"=>"value2"}  
  6.   
  7. solrServer.add doc  
  8.   
  9. solrServer.commit(:commit_attributes => {:waitSearcher=>false:softCommit=>false:expungeDeletes=>true})  
  10. solrServer.optimize(:optimize_attributes => {:maxSegments=>1}) # single segment as output  

No comments: