模块 Abbrev
计算给定字符串集合的无歧义缩写集合。
require 'abbrev' require 'pp' pp Abbrev.abbrev(['ruby']) #=> {"ruby"=>"ruby", "rub"=>"ruby", "ru"=>"ruby", "r"=>"ruby"} pp Abbrev.abbrev(%w{ ruby rules })
生成
{ "ruby" => "ruby", "rub" => "ruby", "rules" => "rules", "rule" => "rules", "rul" => "rules" }
它还提供一个数组核心扩展 Array#abbrev
。
pp %w{ summer winter }.abbrev
生成
{ "summer" => "summer", "summe" => "summer", "summ" => "summer", "sum" => "summer", "su" => "summer", "s" => "summer", "winter" => "winter", "winte" => "winter", "wint" => "winter", "win" => "winter", "wi" => "winter", "w" => "winter" }
常量
- VERSION
公共类方法
abbrev(words, pattern = nil) 点击以切换源代码
给定一组字符串,计算这些字符串的无歧义缩写集合,并返回一个哈希,其中键是所有可能的缩写,值是完整字符串。
因此,如果 words
是 “car” 和 “cone”,则指向 “car” 的键将是 “ca” 和 “car”,而指向 “cone” 的键将是 “co”、“con” 和 “cone”。
require 'abbrev' Abbrev.abbrev(%w{ car cone }) #=> {"ca"=>"car", "con"=>"cone", "co"=>"cone", "car"=>"car", "cone"=>"cone"}
可选的 pattern
参数是一个模式或一个字符串。只有与该模式匹配或以该字符串开头的输入字符串才会包含在输出哈希中。
Abbrev.abbrev(%w{car box cone crab}, /b/) #=> {"box"=>"box", "bo"=>"box", "b"=>"box", "crab" => "crab"} Abbrev.abbrev(%w{car box cone}, 'ca') #=> {"car"=>"car", "ca"=>"car"}
# File abbrev-0.1.2/lib/abbrev.rb, line 74 def abbrev(words, pattern = nil) table = {} seen = Hash.new(0) if pattern.is_a?(String) pattern = /\A#{Regexp.quote(pattern)}/ # regard as a prefix end words.each do |word| next if word.empty? word.size.downto(1) { |len| abbrev = word[0...len] next if pattern && pattern !~ abbrev case seen[abbrev] += 1 when 1 table[abbrev] = word when 2 table.delete(abbrev) else break end } end words.each do |word| next if pattern && pattern !~ word table[word] = word end table end
私有实例方法
abbrev(words, pattern = nil) 点击以切换源代码
给定一组字符串,计算这些字符串的无歧义缩写集合,并返回一个哈希,其中键是所有可能的缩写,值是完整字符串。
因此,如果 words
是 “car” 和 “cone”,则指向 “car” 的键将是 “ca” 和 “car”,而指向 “cone” 的键将是 “co”、“con” 和 “cone”。
require 'abbrev' Abbrev.abbrev(%w{ car cone }) #=> {"ca"=>"car", "con"=>"cone", "co"=>"cone", "car"=>"car", "cone"=>"cone"}
可选的 pattern
参数是一个模式或一个字符串。只有与该模式匹配或以该字符串开头的输入字符串才会包含在输出哈希中。
Abbrev.abbrev(%w{car box cone crab}, /b/) #=> {"box"=>"box", "bo"=>"box", "b"=>"box", "crab" => "crab"} Abbrev.abbrev(%w{car box cone}, 'ca') #=> {"car"=>"car", "ca"=>"car"}
# File abbrev-0.1.2/lib/abbrev.rb, line 74 def abbrev(words, pattern = nil) table = {} seen = Hash.new(0) if pattern.is_a?(String) pattern = /\A#{Regexp.quote(pattern)}/ # regard as a prefix end words.each do |word| next if word.empty? word.size.downto(1) { |len| abbrev = word[0...len] next if pattern && pattern !~ abbrev case seen[abbrev] += 1 when 1 table[abbrev] = word when 2 table.delete(abbrev) else break end } end words.each do |word| next if pattern && pattern !~ word table[word] = word end table end