Flowdock

Calculate the set of unique abbreviations for a given set of strings.

  require 'abbrev'
  require 'pp'

  pp Abbrev::abbrev(['ruby', 'rules']).sort

Generates:

  [["rub", "ruby"],
   ["ruby", "ruby"],
   ["rul", "rules"],
   ["rule", "rules"],
   ["rules", "rules"]]

Also adds an abbrev method to class Array.

Show files where this module is defined (1 file)
Register or log in to add new notes.
February 12, 2009
3 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