Ruby 2.4

Abbrev

模块缩写(module 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" }

公共类方法

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