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