的另一种方法:
my_array = my_string.split.map(&:strip)
substitutions.to_a
.repeated_permutation(subs.size)
.map { |a| Hash[a.uniq] }
.uniq
.map { |h| my_array.map { |w| h.key?(w) ? h[w] : w }.join(' ') }
.concat([my_string])
.uniq
在一些效率的损失,任一个或两个的uniq
前两个出场可以省略。
步骤:
my_string = "yellow dogs are cooler than brown cats"
substitutions = {"yellow"=>"black", "brown"=>"grey", "cooler"=>"neater"}
a = substitutions.to_a # 27 elements
#=> [["yellow", "black"], ["brown", "grey"], ["cooler", "neater"]]
b = a.repeated_permutation(subs.size)
#=> => #<Enumerator: [["yellow", "black"],...
b.to_a
#=> [[["yellow", "black"], ["yellow", "black"], ["yellow", "black"]],
# [["yellow", "black"], ["yellow", "black"], ["brown", "grey"]],
# [["yellow", "black"], ["yellow", "black"], ["cooler", "neater"]],
# [["yellow", "black"], ["brown", "grey"], ["yellow", "black"]],
# ...
# [["cooler", "neater"], ["cooler", "neater"], ["cooler", "neater"]]]
c = b.map {|a| Hash[a.uniq]} # 27 elements
#=> [{"yellow"=>"black"},
# {"brown"=>"grey", "yellow"=>"black"},
# {"cooler"=>"neater", "yellow"=>"black"},
# {"brown"=>"grey", "yellow"=>"black"},
# {"brown"=>"grey", "yellow"=>"black"},
# ...
# {"brown"=>"grey", "cooler"=>"neater", "yellow"=>"black"},
# ...
# {"cooler"=>"neater"}]
d = c.uniq
#=> [{"yellow"=>"black"},
# {"brown"=>"grey", "yellow"=>"black"},
# {"cooler"=>"neater", "yellow"=>"black"},
# {"brown"=>"grey", "cooler"=>"neater", "yellow"=>"black"},
# {"brown"=>"grey"},
# {"brown"=>"grey", "cooler"=>"neater"},
# {"cooler"=>"neater"}]
e = d.map {|h| my_array.map { |w| h.key?(w) ? h[w] : w }.join(' ') }
.concat([my_string])
#=> ["black dogs are cooler than brown cats",
# "black dogs are cooler than grey cats",
# "black dogs are neater than brown cats",
# "black dogs are neater than grey cats",
# "yellow dogs are cooler than grey cats",
# "yellow dogs are neater than grey cats",
# "yellow dogs are neater than brown cats",
# "yellow dogs are cooler than brown cats"]
e.uniq
# No effect here. Only relevant for substitutions such as
# "black=>"yellow" and "grey=>yellow", or "black"=>"black"
嗯。您所需的输出似乎不完整;你不想另外考虑其他两种可能性:'[“黄狗比棕色的猫冷”,“黄狗比灰猫冷”] – grenierm5
感谢您的支持。添加。 – user2270029