Sunday, May 26, 2013

sort(1) in Ruby

As a simple example of using the getoptlong library (as well as an example of various array methods), here is a simple version of the UNIX sort program, implemented in Ruby.

sort.rb


#!/usr/bin/env ruby

require 'getoptlong'

class SortProgram
private
  def do_args
    parser = GetoptLong.new(
      ['-u', '--unique', GetoptLong::NO_ARGUMENT],
      ['-r', '--reverse', GetoptLong::NO_ARGUMENT]
    )

    @unique = false
    parser.each do |opt, arg|
      case opt
      when '-u'
        @unique = true
      when '-r'
        @reverse = true
      end
    end
  end

public
  def main
    do_args
    lines = []
    if ARGV.length > 0
      ARGV.each do |path|
        lines = File.readlines(path)
      end
    else
      lines = File.readlines('/dev/stdin')
    end
    lines.sort!
    if @unique
      lines.uniq!
    end
    if @reverse
      lines.reverse!
    end
    lines.each { |e| print e }
  end
end

program = SortProgram.new
program.main

Consider the sample input:

input.txt


apple
orange
banana
canteloupe
orange

We can sort the input in alphabetical order by

cat input.txt | ./sort.rb

or

./sort.rb input.txt.

The -r or --reverse flags sort in reverse-alphabetical order, and the -u or --unique flags output only unique entries.

No comments:

Post a Comment