Programming Tutorials

Module Abbrev in Ruby

By: Emiley J. in Ruby Tutorials on 2009-03-03  

Given a set of strings, calculate the set of unambiguous abbreviations for those strings, and return a hash where the keys are all the possible abbreviations and the values are the full strings. Thus, given input of "car" and "cone", the keys pointing to "car" would be "ca" and "car", while those pointing to "cone" would be "co", "con", and "cone".

The optional pattern parameter is a pattern or a string. Only those input strings matching the pattern, or begging the string, are considered for inclusion in the output hash

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.

Class Array

Calculates the set of unambiguous abbreviations for the strings in self. If passed a pattern or a string, only the strings matching the pattern or starting with the string are considered.

  %w{ car cone }.abbrev   #=> { "ca" => "car", "car" => "car",
                                "co" => "cone", "con" => cone",
                                "cone" => "cone" }





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)