根据您正在寻找字谜制造者的评论,这是这种野兽的基础:
require 'pp'
require 'set'
words = %w[cream scream scream creams]
hash = Hash.new{ |h,k| h[k] = Set.new }
words.each do |w|
hash[w.downcase.split('').sort] << w.downcase
end
pp hash
=> {["a", "c", "e", "m", "r"]=>#<Set: {"cream"}>,
["a", "c", "e", "m", "r", "s"]=>#<Set: {"scream", "creams"}>}
给定一组单词,这将创建一个散列,其中每个键是单词中字母的排序列表。与该键关联的值是一组具有相同字母的单词。
因为该值是一个集合,所以只存储唯一的单词。
填充该哈希后,您将拥有一个字典,可用于快速查找其他单词。取一个词,以与分解键相同的方式分解它,并将其用作查找中的键:
puts hash['creams'.downcase.split('').sort].to_a.join(', ')
输出:
scream, creams
如果需要重复(和冗余)单词:
require 'pp'
require 'set'
words = %w[cream creams scream scream]
hash = Hash.new{ |h,k| h[k] = [] }
words.each do |w|
hash[w.downcase.split('').sort] << w.downcase
end
pp hash
=> {["a", "c", "e", "m", "r"]=>["cream"],
["a", "c", "e", "m", "r", "s"]=>["creams", "scream", "scream"]}
puts hash['creams'.downcase.split('').sort].to_a.sort.join(', ')
=> creams, scream, scream