Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Monday, April 7, 2014

A Ruby routine to generate Kaprekar numbers

What are Kaprekar numbers ?
Kaprekar numbers are special numbers that were discovered by India mathematician Dattaraya Ramchandra Kaprekar. A more detailed explanation of Kaprekar and his numbers can be found here
http://en.wikipedia.org/wiki/Kaprekar_number
http://en.wikipedia.org/wiki/D._R._Kaprekar
This is a humble effort from my side to pay tribute to this great mathematician. Here is a Ruby routine to generate "n" Kaprekar numbers...

The output might look something like this...

Tuesday, December 17, 2013

How to parse command-line arguments in Ruby using OptionParser

I do my scripting in Ruby. I did a lot of scripting in Perl in the past. Usually people prefer getoptlong in Perl to elegantly process command-line arguments.

As with Ruby, there is more than one way to do a particular thing. Ruby has OptionParser.
OptionParser provides a beautiful framework for processing command-line arguments.

Here is a simple demonstration of its usage :-

#!/usr/bin/ruby

require 'optparse'
 
options = {} # Hash where all the options are stored
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: ./script -f "
  opts.on("-f INPUT_FILE", String,"regression list") do |a|
    options[:input_file] = a.chomp
  end
end

if ARGV.empty?  #In case no arguments are provided, help message is displayed
  puts optparse      #./script -h or --help also displays the usage information
  exit
else
  optparse.parse!
end

regression_list = options[:input_file]

< Rest of the code for dealing with the regression list and simulations etc.>

Note - if you use parse! then ARGV is taken as the input argument by default
If you choose to use parse, then you would have to supply the input list explicitly, e.g., ARGV