Yogi Yogi - 4 months ago 17
Ruby Question

Random replacement of a particular character in file (ruby)

I tried to find a simple solution to replace a particular character randomly within a file.

Unfortunately, my solution replaces all found characters and not just some of them.

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


I appreciate any help, thanks.

Answer

The question is not clear. If you want to replace some random occurrences of a particular (fixed) character (",") with a particular (fixed) character (";"), then do:

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