module
Calculates the set of unique abbreviations for a given set of strings.
require 'abbrev' require 'pp' pp Abbrev.abbrev(['ruby', 'rules'])
Generates:
{ "rub" => "ruby", "ruby" => "ruby", "rul" => "rules", "rule" => "rules", "rules" => "rules" }
It also provides an array core extension, Array#abbrev.
pp %w{summer winter}.abbrev #=> {"summe"=>"summer", "summ"=>"summer", "sum"=>"summer", "su"=>"summer", "s"=>"summer", "winte"=>"winter", "wint"=>"winter", "win"=>"winter", "wi"=>"winter", "w"=>"winter", "summer"=>"summer", "winter"=>"winter"}
Register or
log in
to add new notes.
Soleone -
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