Plough => Ruby

Journey through ruby

Abbreviation in Ruby

Ruby’s standard library is filled with several unique, non-standard classes/modules, one such module is Abbrev.

Abbrev calculates the set of unique abbreviations for a given set of strings. The following code demonstrates it properly:

1
2
3
4
require 'abbrev'
require 'pp'

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

This code produces the following output where all the keys are abbreviated and unique, and point to their respective words.

1
2
3
4
5
{"ruby"=>"ruby",
 "rub"=>"ruby",
 "rules"=>"rules",
 "rule"=>"rules",
 "rul"=>"rules"}

This also provides an extension for an Array, so you can call ‘abbrev’ method straight on an array. The code above will then become:

1
2
3
4
require 'abbrev'
require 'pp'

pp ['ruby', 'rules'].abbrev

I found a couple of use cases of the Abbrev module on Google:

  1. For creating unique labels for a bar graph.

  2. For creating an auto-completer on console, intriguing, right?

Hope this will make you aware of such a nifty module and please share your use-cases with the rest of us.