随机替换文件中的特定字符 (ruby)

Random replacement of a particular character in file (ruby)

我试图找到一个简单的解决方案来随机替换文件中的特定字符。

不幸的是,我的解决方案替换了所有找到的字符,而不仅仅是其中的一些字符。

file_names = ['users_controller.rb']

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(",", ";") #replaces , to ; (unfortunatly all and not just some)
  puts new_contents
  File.open(file_name, "w") {|file| file.puts new_contents }
end

感谢任何帮助,谢谢。

问题不清楚。如果您想用特定(固定)字符(";")替换随机出现的特定(固定)字符(","),则执行:

text.gsub(","){rand(2).zero? ? "," : ";"}