Flowdock

Calculates the set of unambiguous abbreviations for a given set of strings.

require 'abbrev'
require 'pp'

pp Abbrev.abbrev(['ruby'])
#=>  {"ruby"=>"ruby", "rub"=>"ruby", "ru"=>"ruby", "r"=>"ruby"}

pp Abbrev.abbrev(%w{ ruby rules })

Generates:

{ "ruby"  =>  "ruby",
  "rub"   =>  "ruby",
  "rules" =>  "rules",
  "rule"  =>  "rules",
  "rul"   =>  "rules" }

It also provides an array core extension, Array#abbrev.

pp %w{ summer winter }.abbrev

Generates:

{ "summer"  => "summer",
  "summe"   => "summer",
  "summ"    => "summer",
  "sum"     => "summer",
  "su"      => "summer",
  "s"       => "summer",
  "winter"  => "winter",
  "winte"   => "winter",
  "wint"    => "winter",
  "win"     => "winter",
  "wi"      => "winter",
  "w"       => "winter" }
Show files where this module is defined (1 file)
Register or log in to add new notes.
February 12, 2009
4 thanks

Useful scenario

This can be quite useful, for example when writing a command line script which takes a number of options.

Example

Let’s say you want to make a script that can make the basic CRUD operations. So want to be able to call it like this from the command line:

> my_script create
> my_script delete

The following script allows you to use any abbreviated command as long as it is unambiguous.

# my_script.rb
require 'abbrev'

command = ARGV.first
actions = %w[create read update delete]
mappings = Abbrev::abbrev(actions)
puts mappings[command]

That means you can call it like this:

> my_script cr
> my_script d

And it will print:

create
delete