【问题标题】:All possible combinations of selected character substitution in a string in ruby - Improvedruby 中字符串中选定字符替换的所有可能组合 - 改进
【发布时间】:2017-11-14 02:39:17
【问题描述】:

我正在使用来自this answer 的代码,但如果我想使用多个选项来表示您将在下面看到的“s”替换,它只能处理一个。如何使下面的代码更适合这样的替换:

subs = {'a'=>['@'],'i'=>['!'],'s'=>['$','&'] }

这是原始代码和替换。

string = "this is a test"
subs = {'a'=>'@','i'=>'!','s'=>'$'}

keys = subs.keys
combinations = 1.upto(subs.size).flat_map { |i| keys.combination(i).to_a }

combinations.each do |ary|
  new_string = string.dup
  ary.each { |c| new_string.gsub!(c,subs) }
  puts new_string
end

【问题讨论】:

  • 您的 subs 不是有效的 Ruby 表达式。
  • 耀应该把subs = {'a'=>'@','i'=>'!', '*','s'=>'$', 's'=>'&'}写成subs = {'a'=>'@','i'=>'!', '*','s'=>['$','&'] }..这是有效的。
  • 谢谢。我在上面进行了编辑,但它返回给我这样的项目: "th!["$", "&"] !["$", "&"] @ te["$", "&"]t"
  • 不一致不好。您应该一直使用数组。 {'a' => ['@'], ...}.
  • 好的,谢谢。我也改变了上面的。如何获取代码以生成我现在想要的输出?它只是替换数组。

标签: ruby


【解决方案1】:

与您的subs相比,以下包含替换可以空申请的信息会更容易处理:

subs = {"a" => ["a", "@"], "i" => ["i", "!"], "s" => ["s", "$", "&"]}

使用这个,你应该坚持我的回答。以下只是对我对您上一个问题的回答的小修改:

string = "this is a test"

a = subs.values
a = a.first.product(*a.drop(1))

a.each do |a|
  p [subs.keys, a].transpose.each_with_object(string.dup){|pair, s| s.gsub!(*pair)}
end

给出:

"this is a test"
"thi$ i$ a te$t"
"thi& i& a te&t"
"th!s !s a test"
"th!$ !$ a te$t"
"th!& !& a te&t"
"this is @ test"
"thi$ i$ @ te$t"
"thi& i& @ te&t"
"th!s !s @ test"
"th!$ !$ @ te$t"
"th!& !& @ te&t"

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
相关资源
最近更新 更多