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 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 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